从不在python中工作的txt文件解析json

2024-05-23 21:09:25 发布

您现在位置: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)

Tags: 文件nametxtjsondataaswithlogin
2条回答

How to append data to a json file?中所述,使用a模式不是一个好选择,我认为最好手动将获取的数据附加到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)

正如注释中提到的,仅仅将JSON对象一个接一个地连接到文件中并不能使文件成为有效的JSON(并且可以将其解析为单个JSON对象)

最好的最小格式是JSON行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文档的当前文件对您很重要,您可以尝试使用类似于用[]包装文件内容并在格式不正确的连接文档之间添加逗号的黑客方法来修复它,但这并不能保证有效

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

相关问题 更多 >