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