[英]How can I format json via python?
我有一个非常基本的问题,我无法弄清楚。 尝试将对象数据写入 json 文件时,我不断收到“文件末尾预期.json”。 我想知道我该如何解决这个问题? 我通过写一个 for 循环来做到这一点。 不知道如何格式化。
这是有问题的代码
with open("data.json", "w") as outfile:
for x,y in structures.infrastructures.items():
outfile.write(Sector(x, y["Depended on by"],y["Depends on"], y["Sub sections"]).toJson())
这是输出
{
"name": "Chemical",
"depended_on": [
"Critical Manufacturing",
"Nuclear Reactors, Waste, and Material Management",
"Commercial",
"Healthcare and Public Health",
"Food and Agriculture",
"Energy"
],
"depends_on": [
"Emergency Services",
"Energy",
"Food and Agriculture",
"Healthcare and Public Health",
"Information Technology",
"Nuclear Reactors, Waste, and Material Management",
"Transportation Systems",
"Water"
],
"sub_sections": [
"Chemical Plants",
"Chemical Refineries",
"Labs"
],
"Status": 0,
"Strain": 0
}{ -> this is where the error is
"name": "Commercial",
"depended_on": [
....
....
etc
这是我的 toJson 方法:
def toJson(self):
return json.dumps(self, default=lambda o: o.__dict__, indent=4)
但是,是的,我如何在我的对象数据以 JSON 格式编写的地方实现它?
一个有效的 json 文件只能包含一个对象。 将您的数据收集到一个列表中并通过一次调用将其写入,或者使用您的代码模拟格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.