【发布时间】:2018-02-25 15:12:23
【问题描述】:
每一行都是有效的 JSON,但我需要整个文件都是有效的 JSON。
我有一些从 Web 服务聚合并转储到文件中的数据,因此它是 JSON 格式的,但不是有效的 JSON,因此无法以 JSON 文件可以的简单直观方式处理它 - 从而构成颈部的严重疼痛,它看起来(或多或少)像这样:
{"record":"value0","block":"0x79"}
{"record":"value1","block":"0x80"}
我一直在尝试将其重新解释为有效的 JSON,我最近的尝试如下所示:
with open('toy.json') as inpt:
lines = []
for line in inpt:
if line.startswith('{'): # block starts
lines.append(line)
但是,正如您可能从我提出这个问题这一事实推断出来的那样 - 这不起作用 - 关于我如何解决这个问题的任何想法?
编辑:
试过这个:
with open('toy_two.json', 'rb') as inpt:
lines = [json.loads(line) for line in inpt]
print(lines['record'])
但出现以下错误:
Traceback (most recent call last):
File "json-ifier.py", line 38, in <module>
print(lines['record'])
TypeError: list indices must be integers, not str
理想情况下,我想像使用普通 JSON 一样与它进行交互,即data['value']
编辑二
with open('transactions000000000029.json', 'rb') as inpt:
lines = [json.loads(line) for line in inpt]
for line in lines:
records = [item['hash'] for item in lines]
for item in records:
print item
【问题讨论】:
-
每一行都是有效的 JSON 吗?例如:
lines = [json.loads(line) for line in inpt]能完成这项工作吗? -
lines.append(json.loads(line))? -
是的,但我不想处理每一行——我想将文件作为一个整体处理——真正的文件有数百万条记录
-
[json.loads(line) for line in inpt]在什么方面不构成“将文件作为一个整体处理”? -
我现在很困惑。如果这个文件是有效的 JSON,它会是一个列表,对吧?你想把它解释成什么类型?