如何从一个文件中提取多个 JSON 对象? [英] How to extract multiple JSON objects from one file?

查看:33
本文介绍了如何从一个文件中提取多个 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes","代码":[{"event1":"A","re​​sult":"1"},...]}{ID":1A35B",时间戳":20140102",有用性":否","代码":[{"event1":"B","re​​sult":"1"},...]}{ID":AA356",时间戳":20140103",有用性":否","代码":[{"event1":"B","re​​sult":"0"},...]}…

我想将所有时间戳"和有用性"提取到一个数据框中:

 时间戳的用处0 20140101 是1 20140102 否2 20140103 否…

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

解决方案

使用json数组,格式为:

<预><代码>[{ID":12345",时间戳":20140101",有用性":是","代码":[{"event1":"A","re​​sult":"1"},...]},{ID":1A35B",时间戳":20140102",有用性":否","代码":[{"event1":"B","re​​sult":"1"},...]},{ID":AA356",时间戳":20140103",有用性":否","代码":[{"event1":"B","re​​sult":"0"},...]},...]

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

导入json使用 open('file.json') 作为 json_file:数据 = json.load(json_file)

现在数据的内容是一个数组,其中包含代表每个元素的字典.

您可以轻松访问它,即:

data[0]["ID"]

I am very new to Json files. If I have a json file with multiple json objects such as following:

{"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"},…]}
…

I want to extract all "Timestamp" and "Usefulness" into a data frames:

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

Does anyone know a general way to deal with such problems?

解决方案

Use a json array, in the format:

[
{"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"},…]},
...
]

Then import it into your python code

import json

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

    data = json.load(json_file)

Now the content of data is an array with dictionaries representing each of the elements.

You can access it easily, i.e:

data[0]["ID"]

这篇关于如何从一个文件中提取多个 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆