【问题标题】:How to read this JSON file?如何读取这个 JSON 文件?
【发布时间】:2018-10-04 03:04:32
【问题描述】:

我有一个如下所示的 JSON 文件:

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)

但它无法通过。有什么想法可以读取第一行上的数字和不同对象中尾随的数据吗?

【问题讨论】:

  • 试试json.loads
  • 您可以将您的 json 文件的 sn-p 发布为文本吗?我会赞成:)
  • 该文件的内容不是有效的 JSON 格式,因此您需要做一些事情来解决这个问题。

标签: python json


【解决方案1】:

阅读第一行,然后将其他所有内容发送到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 被随意分解,您必须在解析之前进行一些手动重建。

【讨论】:

  • 如果你放弃了next,你就不需要.strip()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多