我正在尝试从本地主机 URL 逐行获取 JSON 数据并将其插入到 JSON 文件中。当我尝试打开该文件时,收到一条错误消息:多个 JSON 根元素
。
import urllib.parse
import urllib.request, json
import json
abc={}
for i in range(6666,6669):
print(i)
full_url="http://localhost/get/info" + str(i)
with urllib.request.urlopen(full_url) as url:
data = json.loads(url.read().decode())
print(data['id'])
abc={i:[data]}
with open('data.json', 'a') as outfile:
json.dump(abc,outfile)
最佳答案
一个有效的 json 对象必须只有一个根
参见How to read a JSON file containing multiple root elements?
必须将所有json对象追加到一个数组中,然后写入json文件
生成的 json 对象必须类似于
[
{ object 1 },
{ object 2 }
]
请注意,json 中只有一个根对象,该数组包含所有其他对象
关于python - 将 json 数据写入 json 文件时 JSON.parse 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55308091/