I have a input file which contains a sequence(not necessarily a list/tuple etc..) of JSON elements.
This is the sample data:
{
"candidate":[
{
"id":"25624",
"name":"Clinton",
"affiliation":"Democrat",
"color":"",
"value":"46.8",
"status":"1"
},
{
"id":"25623",
"name":"Trump",
"affiliation":"Republican",
"color":"",
"value":"43.6",
"status":"1"
}
],
"date":"Tue, 08 Nov 2016 00:00:00 -0600" }, {
"candidate":[
{
"id":"25624",
"name":"Clinton",
"affiliation":"Democrat",
"color":"",
"value":"47.0",
"status":"1"
},
{
"id":"25623",
"name":"Trump",
"affiliation":"Republican",
"color":"",
"value":"43.8",
"status":"1"
}
],
"date":"Mon, 07 Nov 2016 00:00:00 -0600" }
I am trying to use JSON library which can read first block of JSON but errs out when reading multiple blocks.
What is the right way to read multiple JSON elements in Python.
Thanks in advance!!
答案 0 :(得分:0)
您想要做的是创建一个生成器函数,并利用如何在Python中实现json。这是我使用生成器函数的工作示例:
import json
from splitstream import splitfile
def generate_json(file_name):
for jsonstr in splitfile(open(file_name), format="json"):
yield json.loads(jsonstr)
for item in generate_json('data.json'):
print item
但是,您可能需要安装splitstream(通过pip)并在代码中包含生成器函数generate_json。这个函数的作用是每次完成时生成(返回)一个json对象。