[英]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.