簡體   English   中英

在python中創建有效的json對象

[英]create valid json object in python

每行都是有效的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文檔。

這是“ JSON行”格式( http://jsonlines.org/

嘗試獨立處理每行( json.loads(line) )或使用專門的庫( https://jsonlines.readthedocs.io/en/latest/ )。

def process(oneline):
    # do what you want with each line
    print(oneline['record'])

with open('toy_two.json', 'rb') as inpt:
    for line in inpt:
        process(json.loads(line))

看起來像我最近使用的NDJSON。 規范在這里 ,我不確定它的用處。 請問以下工作嗎?

with open('the file.json', 'rb') as infile:
    data = infile.readlines()
    data = [json.loads(item.replace('\n', '')) for item in data] 

這應該給您詞典列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM