3 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
使用json數(shù)組,格式為:
[
{"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"},…]},
...
]
然后將其導(dǎo)入您的python代碼
import json
with open('file.json') as json_file:
data = json.load(json_file)
現(xiàn)在,數(shù)據(jù)的內(nèi)容是一個(gè)數(shù)組,其中的字典代表每個(gè)元素。
您可以輕松訪問它,即:
data[0]["ID"]

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以使用json.JSONDecoder.raw_decode任意解碼大量“堆疊”JSON字符串(只要它們可以適合內(nèi)存)。raw_decode一旦它有一個(gè)有效的對(duì)象就停止,并返回不在解析對(duì)象中的最后一個(gè)位置。它沒有記錄,但您可以將此位置傳回,raw_decode并從該位置再次開始解析。不幸的是,Python json模塊不接受具有前綴空格的字符串。所以我們需要搜索以找到文檔的第一個(gè)非空白部分。
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)
打?。?/p>
{'a': 1}
[1, 2]
添加回答
舉報(bào)