每一行都是有效的JSON,但是我需要將整個文件作爲有效的JSON。在python中創建有效的json對象
我有一些數據是從一個Web服務聚合並轉儲到一個文件,所以它是JSON-eaque,但不是有效的JSON,因此無法以簡單直觀的方式處理JSON文件 - 從而consituting一個重大的痛苦在脖子,它看起來像這樣(或多或少):
{"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']
編輯II
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?例如:'行= [json.loads(line)inline in inpt]'做這項工作? –
'lines.append(json.loads(line))'? –
是的,但我不想處理每一行 - 我想整個處理文件 - 真實的文件有數百萬條記錄 –