簡體   English   中英

使用 Python 將字典轉換為 json 文件

[英]Dictionary to a json file using Python

我想使用 csv 文件中的值和代碼中定義的值創建字典。 然后需要將其寫入 json 文件。

以下鏈接中的圖像顯示了附加到 df 時 csv 中的數據。

數據

下面的鏈接包含我在 csv 文件中使用的數據https://docs.google.com/spreadsheets/d/1RW9yZUWLHGXwRAxiOUchK8UkycMg2WfrX9DZwHNTjEY/edit?usp=drive_web&ouid=112366564296100909730

我使用了以下代碼。

import json
import pandas as pd

df = pd.read_csv('text.csv')

dict = {}

for index, row in df.iterrows():
    a = "aaa"
    u = "uuu"
    g = str(row['animal'])
    h = str(row['characteristic'])


    dict.update({
        "journal": [
            [f"{a}",f"{g}"],
            [f"t_s{u}",f"{h}"]
        ]})


    with open('web.json', 'a') as file:
        json.dump(dict, file)
        file.write('\n')

上面在“web.json”文件中給出了如下輸出

{"journal": [["aaa", "dog"], ["t_suuu", "four legs"]]}
{"journal": [["aaa", "cat"], ["t_suuu", "four legs"]]}
{"journal": [["aaa", "cow"], ["t_suuu", "four egs"]]}
{"journal": [["aaa", "bird"], ["t_suuu", "two legs"]]}
{"journal": [["aaa", "ant"], ["t_suuu", "six legs"]]}

與其在每個循環中使用dict記錄數據並保存到 JSON 文件,不如在每個循環中使用List並將對象附加到列表中。 循環退出后,將該數據列表(對象數組)轉儲到 JSON 文件。

import json
import pandas as pd

df = pd.read_csv('text.csv')

dict = []

for index, row in df.iterrows():
    a = "aaa"
    u = "uuu"
    g = str(row['animal'])
    h = str(row['characteristic'])


    dict.append({
        "journal": [
            [f"{a}",f"{g}"],
            [f"t_s{u}",f"{h}"]
        ]})


with open('web.json', 'a') as file:
    json.dump(dict, file)

# Later you can delete `dict` (containing objects array) variable from memory
# del dict

你可以試試下面的代碼

import json
import pandas as pd

df = pd.read_csv('text.csv')

final_data = []
for index, row in df.iterrows():
    dict = {}
    for key,value in zip(row.index, row.values):
        dict[key] = value

    final_data.append(dict)


with open('web.json', 'w') as file:
    json.dump(final_data, file)

正如@pratik-ghodke 提到的,您應該使用List而不是dict來存儲數據,然后將List轉儲到 json 文件。

上面的代碼會將數據存儲到 web.json 文件中,格式如下

[{"animal": "dog", "characteristic": "four legs", "groups": "mammal"}, {"animal": "cat", "characteristic": "four legs", "groups": "mammal"}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM