python - 如何从一个文件中提取多个 JSON 对象?

我对 Json 文件非常陌生。如果我有一个包含多个 json 对象的 json 文件,例如:

{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
 "Code":[{"event1":"A","result":"1"},…]}
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
 "Code":[{"event1":"B","result":"1"},…]}
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
 "Code":[{"event1":"B","result":"0"},…]}
…

我想将所有“时间戳”和“有用性”提取到数据框中:

    Timestamp    Usefulness
 0   20140101      Yes
 1   20140102      No
 2   20140103      No
 …

有没有人知道处理此类问题的一般方法?

最佳答案

更新:我编写了一个不需要一次性读取整个文件的解决方案。对于 stackoverflow 的答案来说太大了,但可以在这里找到 jsonstream .

您可以使用 json.JSONDecoder.raw_decode 来解码任意大的“堆叠”JSON 字符串(只要它们可以放入内存)。 raw_decode 一旦它有一个有效的对象就停止并返回不属于已解析对象的最后一个位置。它没有记录,但您可以将此位置传递回 raw_decode 并从该位置重新开始解析。不幸的是,Python json 模块不接受带有前缀空格的字符串。所以我们需要搜索文档的第一个非空白部分。

from json import JSONDecoder, JSONDecodeError
import re

NOT_WHITESPACE = re.compile(r'\S')

def decode_stacked(document, pos=0, decoder=JSONDecoder()):
    while True:
        match = NOT_WHITESPACE.search(document, pos)
        if not match:
            return
        pos = match.start()
        
        try:
            obj, pos = decoder.raw_decode(document, pos)
        except JSONDecodeError:
            # do something sensible if there's some error
            raise
        yield obj

s = """

{"a": 1}  


   [
1
,   
2
]


"""

for obj in decode_stacked(s):
    print(obj)

打印:

{'a': 1}
[1, 2]

https://stackoverflow.com/questions/27907633/

相关文章:

iphone - 从 NSArray 创建一个 json 字符串

python - 如果键可能不存在,则从 Python dict 读取

c# - 在 Json.net 中获取错误 "Cannot add or remove items

python - json.dumps 打乱了顺序

json - 从 PostgreSQL 中的函数返回中删除双引号

javascript - 如何在 console.log 中打印 JSON 数据?

python - 避免 KeyError 的默认字典键

json - 以 JSON 格式访问(新型、公共(public))Google 工作表

json - HTTPResponse 对象 -- JSON 对象必须是 str,而不是 'byte

android - 在 adb logcat 输出中格式化 json 字符串