3

我正在尝试逐行从本地主机 URL 获取 JSON 数据并将其插入 JSON 文件。当我尝试打开文件时,我收到一条错误消息,显示Multiple JSON root elements.

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)

4

1 回答 1

0

一个有效的 json 对象必须只有一个根

请参阅如何读取包含多个根元素的 JSON 文件?

您必须将所有 json 对象附加到数组中,然后将其写入 json 文件

生成的 json 对象必须像

[
{ object 1 },
{ object 2 }
]

请注意,json 中只有一个根对象,该数组包含所有其他对象

于 2019-03-22T22:47:01.697 回答