小编典典

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

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
 …

有谁知道解决此类问题的一般方法?


阅读 558

收藏
2020-07-27

共1个答案

小编典典

使用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"},…]},
...
]

然后将其导入到您的python代码中

import json

with open('file.json') as json_file:

    data = json.load(json_file)

现在,数据的内容是一个带有字典的数组,字典表示每个元素。

您可以轻松访问它,即:

data[0]["ID"]
2020-07-27