[英]Generate a JSON file with Python
我正在嘗試用 python 生成一個 JSON 文件。 但我無法弄清楚如何正確附加每個對象並將它們一次寫入 JSON 文件。 你能幫我解決這個問題嗎? a、b 和 x、y、z 的值在腳本中計算。 太感謝了
這就是生成的 JSON 文件的樣子
{
"a": {
"x": 2,
"y": 3,
"z": 4
},
"b": {
"x": 5,
"y": 4,
"z": 4
}
}
這是python腳本
import json
for i in range(1, 5):
a = geta(i)
x = getx(i)
y = gety(i)
z = getz(i)
data = {
a: {
"x": x,
"y": y,
"z": z
}}
with open('data.json', 'a') as f:
f.write(json.dumps(data, ensure_ascii=False, indent=4))
在構建 JSON 時只需使用 python 中的普通字典,然后使用 JSON 包導出到 JSON 文件。
你可以像這樣構造它們(很長的路):
a_dict = {}
a_dict['id'] = {}
a_dict['id']['a'] = {'properties' : {}}
a_dict['id']['a']['properties']['x'] = '9'
a_dict['id']['a']['properties']['y'] = '3'
a_dict['id']['a']['properties']['z'] = '17'
a_dict['id']['b'] = {'properties' : {}}
a_dict['id']['b']['properties']['x'] = '3'
a_dict['id']['b']['properties']['y'] = '2'
a_dict['id']['b']['properties']['z'] = '1'
或者你可以使用一個函數:
def dict_construct(id, x, y, z):
new_dic = {id : {'properties': {} } }
values = [{'x': x}, {'y': y}, {'z':z}]
for val in values:
new_dic[id]['properties'].update(val)
return new_dic
return_values = [('a', '9', '3', '17'), ('b', '3', '2', '1')]
a_dict = {'id': {} }
for xx in return_values:
add_dict = dict_construct(*xx)
a_dict['id'].update(add_dict)
print(a_dict)
兩者都給你作為字典:
{'id': {'a': {'properties': {'x': '9', 'y': '3', 'z': '17'}}, 'b': {'properties': {'x': '3', 'y': '2', 'z': '1'}}}}
使用 json.dump:
with open('data.json', 'w') as outfile:
json.dump(a_dict, outfile)
你得到一個文件:
{
"id": {
"a": {
"properties": {
"x": "9",
"y": "3",
"z": "17"
}
},
"b": {
"properties": {
"x": "3",
"y": "2",
"z": "1"
}
}
}
}
確保你有一個有效的 python 字典(看起來你已經這樣做了)
我看到您正在嘗試將您的 json 寫入文件中
with open('data.json', 'a') as f:
f.write(json.dumps(data, ensure_ascii=False, indent=4))
您正在“a”(追加)模式下打開 data.json,因此您將 json 添加到文件的末尾,這將導致錯誤的 json data.json 已經包含任何數據。 改為這樣做:
with open('data.json', 'w') as f:
# where data is your valid python dictionary
json.dump(data, f)
一種方法是一次創建整個字典:
data = {}
for i in range(1, 5):
name = getname(i)
x = getx(i)
y = gety(i)
z = getz(i)
data[name] = {
"x": x,
"y": y,
"z": z
}
然后保存
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.