繁体   English   中英

从 txt 文件中解析 json 在 python 中不起作用

[英]parse json from txt file not working in python

我正在尝试从 python 中的 txt 文件中提取数据,这是一个 json 转储。 但我收到JSONDecode 错误

这就是我将 json 响应添加到文件中的方式

repo=requests.get(url,headers=headers,params=params).json()
if repo:
    with open('data.txt', 'a') as f:
        json.dump(repo, f, sort_keys=True, indent=4)
    continue
else:
    break

这是我的 json 结构

[
    {
        "login": "asu",
        "login_name": "heylo"
    },
    {
        "login": "sr9",
        "login_name": "heylo"
    }
],
[
    {
        "login": "tokuda109",
        "login_name": "mojombo"
    },
    {
        "login": "svallory",
        "login_name": "mojombo"
    }
]

这是我要提取的

with open('data.txt') as fd:
    json_data = json.load(fd)
    pprint(json_data)

正如评论中所提到的,只是将 JSON 对象一个接一个地连接到一个文件中并不能生成一个有效的 JSON 文件(并且可以将其解析为单个 Z0ECD11C1D7A287401D148A2F8Z 对象)。

最小更好的格式是 JSON Lines, https://jsonlines.org/ ,这是一个文件,每个文件都是一个 JSON 文档。

您可以通过附加到文件来创建这样的文件,同时确保在转储 JSON 时关闭indent

with open('data.txt', 'a') as f:
    print(json.dumps(repo, sort_keys=True), file=f)

使用print()确保尾随换行符。

然后,您可以使用例如加载数据

with open('data.txt') as fd:
    json_data = [json.loads(line) for line in fd if line.strip()]

如果连接 JSON 文档的当前文件对您很重要,您可以尝试使用 hack 修复它,例如用[]包装文件的内容并在其他格式错误的连接文档之间添加逗号,但这并不能保证有效。

with open('data.txt') as fd:
    fixed_json_data = json.loads("[" + fd.read().replace("}{", "},{") + "]")

如何将 append 数据写入 json 文件中所述? a模式不是一个好的选择,我认为append 手动将数据提取到data.txt中的可用列表中更好,如下所示:

import json
import requests


def read_content():  # reads and returns the available list in data.txt
    try:
        with open('data.txt') as fd:
            json_data = json.load(fd)
    except:
        json_data = []  # handle the first write, when the file does not exist
    return json_data


url = 'https://api.github.com/users/sferik/followers?per_page=100&page=1'
repo = requests.get(url).json()  # repo is a list

if repo:
    available_content = read_content()  # read available list in data.txt
    available_content.extend(repo)  # extend new list to the end of available list
    with open('data.txt', 'w') as f:  # write again, the mode is 'w'
        json.dump(repo, f, sort_keys=True, indent=4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM