python - 如何解析包含多个对象的单行 json 文件
问题描述
我需要读取一些 JSON 数据进行处理。我有一个包含多个 JSON 对象的单行文件,我该如何解析它?
我希望输出是一个文件,每个对象只有一行。
我尝试了一种蛮力方法,它将递归地使用 json.loads 来检查 json 是否有效,但每次运行程序时都会得到不同的结果
import json
with open('sample.json') as inp:
s = inp.read()
jsons = []
start, end = s.find('{'), s.find('}')
while True:
try:
jsons.append(json.loads(s[start:end + 1]))
print(jsons)
except ValueError:
end = end + 1 + s[end + 1:].find('}')
else:
s = s[end + 1:]
if not s:
break
start, end = s.find('{'), s.find('}')
for x in jsons:
writeToFilee(x)
json格式可以看这里 https://pastebin.com/DgbyjAG9
解决方案
为什么不直接使用 的pos
属性JSONDecodeError
来告诉你在哪里划界呢?
就像是:
import json
def json_load_all(buf):
while True:
try:
yield json.loads(buf)
except json.JSONDecodeError as err:
yield json.loads(buf[:err.pos])
buf = buf[err.pos:]
else:
break
与您的演示数据一起使用:
with open('data.json') as fd:
arr = list(json_load_all(fd.read()))
正好给了我两个元素,但我想你还有更多?
要使用标准库完成此操作,写出如下所示:
with open('data.json') as inp, open('out.json', 'w') as out:
for obj in json_load_all(inp.read()):
json.dump(obj, out)
print(file=out)
否则这个jsonlines
包很适合处理这种数据格式
推荐阅读
- javascript - (javascript) 如何在表格 html 上像 classList.toggle 一样隐藏和显示 innerHTML?
- python - 将 ESPN 当前周的 NFL 行刮到 pandas 数据框中
- html - 如何在页面上随机放置背景元素?
- html - 为什么我不能为锚元素设置样式?
- postgresql - 如何使用 SQL 平均数天的每小时值
- php - 在 PHP 中序列化/反序列化布尔数据
- python - 如何在熊猫的多级列中将列名呈现为单个单元格?
- gluon - charm-glisten 6.0.7 命名不一致是意外吗?
- javascript - 如何使用 Canvas 显示 JavaScript 对象?
- postgresql - C3P0 - 具有 maxConnectionAge 的单一连接