やりたいこと
ExcelやCSVの表形式のデータをJsonファイルに出力するにはどのようにしたらいいでしょうか?
Pandasを使ってやってみたりしましたが、そもそもどこからやっていいかわからず質問させていただきました。
追記
階層1の中に階層2、階層3を入れていきたいのと、
階層の深さによらず、最下層と所有者を辞書形式にしたいです。
操作前データ
階層1 | 階層2 | 階層3 | 所有者 |
---|---|---|---|
果物 | 赤 | りんご | A |
果物 | 赤 | いちご | A |
果物 | 黄色 | ばなな | B |
果物 | 黄色 | れもん | C |
野菜 | 赤 | にんじん | C |
野菜 | 赤 | とまと | A |
野菜 | 緑 | きゅうり | B |
野菜 | 緑 | せろり | A |
その他 | 赤 | B | |
その他 | 黄色 | A |
期待するoutput
JSON
1{ 2 "果物": { 3 "赤": [ 4 { 5 "りんご": "A", 6 "いちご": "A" 7 } 8 ], 9 "黄色": [ 10 { 11 "ばなな": "B", 12 "れもん": "C" 13 } 14 ] 15 }, 16 "野菜": { 17 "赤": [ 18 { 19 "にんじん": "C", 20 "とまと": "A" 21 } 22 ], 23 "緑": [ 24 { 25 "きゅうり": "B", 26 "せろり": "A" 27 } 28 ] 29 }, 30 "その他": { 31 "赤": "B.", 32 "黄色": "A" 33 } 34}
やってみたこと
以下のコードを実行してみましたが、その他の最終階層に所有者の値が入りません。
Python
1import pandas as pd 2import json 3 4# Read the Excel file 5df = pd.read_excel('sample.xlsx') 6 7# Create a dictionary to hold the data 8data = {} 9 10# Iterate over the rows of the DataFrame 11for index, row in df.iterrows(): 12 # Create a reference to the dictionary for the current row 13 current_dict = data 14 15 # Iterate over the values in the row 16 for i, value in enumerate(row[:-1]): 17 # If the value is not empty, use it as a key in the dictionary 18 if not pd.isna(value): 19 # If the key does not exist in the dictionary, create it 20 if value not in current_dict: 21 # If this is the last column, the value is the owner 22 if i == len(row)-2: 23 current_dict[value] = row[-1] 24 # Otherwise, create a new dictionary 25 else: 26 current_dict[value] = {} 27 # Update the reference to the dictionary for the current row 28 current_dict = current_dict[value] 29 30# Convert the dictionary to JSON and write it to a file 31with open('example.json', 'w') as f: 32 json.dump(data, f, ensure_ascii=False, indent=4)
出力結果(example.json)
Json
1{ 2 "果物": { 3 "赤": { 4 "りんご": "A", 5 "いちご": "A" 6 }, 7 "黄色": { 8 "ばなな": "B", 9 "れもん": "C" 10 } 11 }, 12 "野菜": { 13 "赤": { 14 "にんじん": "C", 15 "とまと": "A" 16 }, 17 "緑": { 18 "きゅうり": "B", 19 "せろり": "A" 20 } 21 }, 22 "その他": { 23 "赤": {}, 24 "黄色": {} 25 } 26}

回答3件
あなたの回答
tips
プレビュー