前提
Excelから読みだしたdataframeに対し、とある自作のアプリケーションに対して使用するパラメータファイルを
自動生成する仕組みとを作りたいと考えています。
実現したいこと
下記の図のように、Excelから読みだしたdataframeを変換して、label_listの項目に、labelの一覧を、
settingの項目に、それぞれのラベルごとに、各列のデータを項目ごとに区切ってlist化したものを
格納しようと考えています。
発生している問題・エラーメッセージ
上記を実現するために下記のようなスクリプトを書いたのですが、
jsonの入れ子構造が再現できず困っています。
ループ内の文字列が、図のようなフォーマットとならず、json出力すると、下記エラーが出てしまいます。
エラー内容
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_17528/3905920474.py in <module>
1 df = pd.read_excel("test.xlsx")
----> 2 write_json_param(df)
~\AppData\Local\Temp/ipykernel_17528/2183125372.py in write_json_param(tmp_df)
28 # with open(write_filename, "w") as f:
29 with open(write_filename, "w", encoding="CP932") as f:
---> 30 json.dump(write_str, f, ensure_ascii=False)
~\AppData\Local\Programs\Python\Python39\lib\json_init_.py in dump(obj, fp, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
177 # could accelerate with writelines in some versions of Python, at
178 # a debuggability cost
--> 179 for chunk in iterable:
180 fp.write(chunk)
181
~\AppData\Local\Programs\Python\Python39\lib\json\encoder.py in _iterencode(o, _current_indent_level)
429 yield from _iterencode_list(o, _current_indent_level)
430 elif isinstance(o, dict):
--> 431 yield from _iterencode_dict(o, _current_indent_level)
432 else:
433 if markers is not None:
~\AppData\Local\Programs\Python\Python39\lib\json\encoder.py in _iterencode_dict(dct, _current_indent_level)
403 else:
404 chunks = _iterencode(value, _current_indent_level)
--> 405 yield from chunks
406 if newline_indent is not None:
407 _current_indent_level -= 1
~\AppData\Local\Programs\Python\Python39\lib\json\encoder.py in _iterencode(o, _current_indent_level)
436 raise ValueError("Circular reference detected")
437 markers[markerid] = o
--> 438 o = _default(o)
439 yield from _iterencode(o, _current_indent_level)
440 if markers is not None:
~\AppData\Local\Programs\Python\Python39\lib\json\encoder.py in default(self, o)
177
178 """
--> 179 raise TypeError(f'Object of type {o.class.name} '
180 f'is not JSON serializable')
181
TypeError: Object of type set is not JSON serializable
ソースコード
python3
1def write_json_param(tmp_df): 2 # jsonのパラメータ書込み部 3 write_filename = ( 4 # Path(const.MyConst.SETTING_PATH) / f"{sel_schema}_{sel_proc}.json" 5 Path("db_settings_.json") 6 ) 7 8 str_loop = "" 9 for row in df.itertuples(): 10 print(row[1], row[2], row[3], row[4], row[5]) 11 tmp_str = (f"{row[1]}" + ":{" + 12 "x:" + f"[{row[2]}]" + "," + 13 "x1:" + f"[{row[3]}]" + "," + 14 "y1:" + f"[{row[4]}]" + "," + 15 "y2:" + f"[{row[5]}]" + 16 17 "}") 18 str_loop = str_loop + tmp_str + ',' 19 20 write_loop_str = f'"proc_setting":{str_loop}' 21 write_str = { 22 "label_list": tmp_df["label"].tolist(), 23 "setting":{ 24 write_loop_str 25 } 26 # write_loop_str 27 } 28 # with open(write_filename, "w") as f: 29 with open(write_filename, "w", encoding="CP932") as f: 30 json.dump(write_str, f, ensure_ascii=False) 31 32# main処理 33df = pd.read_excel("test.xlsx") 34write_json_param(df) 35
補足情報(FW/ツールのバージョンなど)
Python 3.9.6
回答1件
あなたの回答
tips
プレビュー