我对 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/