python - 将 json 数据写入 json 文件时 JSON.parse 错误

标签 python json python-3.x file-handling python-jsonschema

我正在尝试从本地主机 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/

相关文章:

python - url_for : how to look into another folder other than static

python - pytest-mocks 并声明类级别的固定装置

javascript - node.js TypeError : path must be absolute or specify root to res. sendFile [无法解析JSON]

javascript - 如何将错误消息关联到 json 响应中的 'error' 键

python - 在 Python 中有效比较两个文件中的行

python - 在 Pandas DataFrames 中找到最近点

javascript - 如何将JSON数据转换为日期时间格式?

python - Pandas 线图(按月),按带有时间戳的 SQL 导出的行业分组

python - 使用索引切片打印字符串中的每个单词

python - 使用现有数据框中的数据在 Pandas 的数据框中添加列