2017-07-25 227 views
1

我有一个JSON文件看起来像这样阅读JSON文件在python

20219 
{"topic":"electronics","question":"What is the effective differencial effective of this circuit","excerpt":"I'm trying to work out, in general terms, the effective capacitance of this circuit (see diagram: http://i.stack.imgur.com/BS85b.png). \n\nWhat is the effective capacitance of this circuit and will the ...\r\n  "} 
{"topic":"electronics","question":"Heat sensor with fan cooling","excerpt":"Can I know which component senses heat or acts as heat sensor in the following circuit?\nIn the given diagram, it is said that the 4148 diode acts as the sensor. But basically it is a zener diode and ...\r\n  "} 
{"topic":"electronics","question":"Outlet Installation--more wires than my new outlet can use [on hold]","excerpt":"I am replacing a wall outlet with a Cooper Wiring USB outlet (TR7745). The new outlet has 3 wires coming out of it--a black, a white, and a green. Each one needs to be attached with a wire nut to ...\r\n  "} 
{"topic":"electronics","question":"Buck Converter Operation Question","excerpt":"i have been reading about the buck converter, and have also referred to the various online resources like here.\n\n\n\nIn the above circuit, as I understand, when switch closes, current starts to increase ...\r\n  "} 
{"topic":"electronics","question":"Urgent help in area of ASIC design, verification, SoC [on hold]","excerpt":"I need help with deciding on a Master's Project and I need some ideas related to the field of ASIC Design/ verification or something related to SoC's, FPGA and or combination. I wish to pursue the ...\r\n  "} 

的第一行是一个数(= 20219),这是基本上的文件,随后的数据记录数。我尝试使用以下各项

import json 
with open('training_json.json') as data_file:  
    ndocs = json.readlines(data_file)[0] 

with open('training_json.json') as data_file: 
    next(data_file) 
    docs = json.load(data_file) 

,但打不通。任何想法如何读取第一行的数字以及下面的数据在不同的对象中?

+1

试试'json.loads'。 –

+1

你可以发布你的json文件的片段作为文本?我会upvote :) –

回答

5

阅读的第一行,然后发送一切解析到json.loads()

with open("training_json.json") as data_file: 
    number = next(data_file).strip() 
    your_json = json.loads(data_file.read()) 

如果你有每行不同的JSON对象(因为它从你的形象出现),然后读取其他行逐线,并存储在一个列表:

with open("training_json.json") as data_file: 
    number = next(data_file).strip() 
    your_jsons = [json.loads(line) for line in data_file] 

如果你的JSON是haphazzardly细分上线,你将有你得到它解析之前做一些手工重建。

+0

如果你放弃它,你不需要'.strip()'在'next'之后。 –