简体   繁体   English

从 python json 文件获取多个值

[英]Getting multiple values from python json file

I have this json file我有这个 json 文件

{"tstp":1383173780727,"ststates":[{"nb":901,"state":"open","freebk":6,"freebs":14},{"nb":903,"state":"open","freebk":2,"freebs":18}]}{"tstp":1383173852184,"ststates":[{"nb":901,"state":"open","freebk":6,"freebs":14}]}

I want to take all the values of nb while inside the first tstp only and stop when reaching the other tstp.我只想在第一个 tstp 内获取 nb 的所有值,并在到达另一个 tstp 时停止。

What I am trying to do is to create a file for each tstp and inside this file, it will have nb, state, freebk, freebs as columns in this file.我想要做的是为每个 tstp 创建一个文件,在这个文件中,它将 nb、state、freebk、freebs 作为这个文件中的列。

First time asking a question here...第一次在这里问问题。。。

This is an interesting problem.这是一个有趣的问题。 It appears that you have multiple JSON files just concatenated together in a file and want to split them.看起来您有多个 JSON 文件刚刚在一个文件中连接在一起并且想要拆分它们。 Since the python JSON library only works with complete JSON files and does not accept multiples, it is not sufficient on its own.由于 python JSON 库仅适用于完整的 JSON 文件并且不接受倍数,因此它本身是不够的。

Fortunately, Python has really great error handling that you can take advantage of here.幸运的是,Python 具有非常好的错误处理功能,您可以在这里加以利用。

def json_split(text):
    '''Split text into JSON files and yield each JSON object.'''
    while text:
        try:
            yield json.loads(text)
            return
        except json.JSONDecodeError as error:
            yield json.loads(text[:error.pos])
            text = text[error.pos:].strip()

Then:然后:

with open('some_file.json') as file:
    text = file.read()
for json_object in json_split(text):
    print('json_object = ' + repr(json_object))

The function json_split works by try ing to parse a JSON object, which then fails if there are more than one JSON objects. function json_split通过try解析 JSON object 来工作,如果有多个 JSON 对象,则解析失败。 Fortunately, the JSONDecodeError that results when it fails tells us exactly which position the next JSON object starts at ( pos ), so we just split the string there, parse the JSON, and then rinse and repeat.幸运的是,失败时产生的JSONDecodeError准确地告诉我们下一个 position JSON object 从 ( pos ) 开始,所以我们只是在那里拆分字符串,解析 JSON,然后冲洗并重复。

There are more efficient ways to do this (eg using virtual files or views from the io module to cut down on memory copying), but the above will work well for short collections of files.有更有效的方法来做到这一点(例如,使用虚拟文件或来自io模块的视图来减少 memory 复制),但是上面的方法对于短文件 collections 很有效。

Edit: Also, to write the files back out, just use json.dump , example below.编辑:此外,要将文件写回,只需使用json.dump ,示例如下。

for v in json_split(text):
    with open(str(v['tstp']) + '.json', 'w') as file:
        json.dump(v, file)

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

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