簡體   English   中英

如何修復此錯誤json.decoder.JSONDecodeError:Python

[英]How to fix this error json.decoder.JSONDecodeError: Python

有人可以告訴我為什么這段代碼只能運行一次,而第二次卻出現錯誤我的代碼:

import json

counter_value = 1
data= {}
data['test_device']= []
data['test_device'].append({ "device": "gas_zaehler", "measure": "energy","value": counter_value})

with open('test.json', 'a') as feedjson:
    json.dump(data, feedjson)
    feedjson.write('\n')
    feedjson.close()

with open('test.json') as feedjson:
    json_data = json.load(feedjson)
for i in json_data['test_device']:
    print("device" + i['device'] )

在第二次執行我得到這個錯誤

  File "/usr/lib/python3.5/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 78)

它與下面的鏈接不一樣,因為我沒有兩個字典{} {}: Python json.loads顯示ValueError:額外數據

閱讀您的代碼,我懷疑您的真實意圖是:

  • test.json只能只包含一個字典。
  • 該詞典應具有一個包含列表的鍵“ test_device”。
  • 每次程序執行時,都應在該列表后附加一個新元素。

如果是這種情況,那么您不應該每次都創建一個新詞典並將其附加到文件中。 您應該編寫一個字典,該字典將完全覆蓋其本身的舊版本。

import json

try: #does the data structure exist yet? Let's try opening the file...
    with open("test.json") as feedjson:
        json_data = json.load(feedjson)
except FileNotFoundError: #this must be the first execution. Create an empty data structure.
    json_data = {"test_device": []}

json_data['test_device'].append({ "device": "gas_zaehler", "measure": "energy","value": 1})

#overwrite the old json dict with the updated one
with open("test.json", "w") as feedjson:
    json.dump(json_data, feedjson)

for i in json_data['test_device']:
    print("device" + i['device'] )

結果:

C:\Users\Kevin\Desktop>test.py
devicegas_zaehler

C:\Users\Kevin\Desktop>test.py
devicegas_zaehler
devicegas_zaehler

C:\Users\Kevin\Desktop>test.py
devicegas_zaehler
devicegas_zaehler
devicegas_zaehler

暫無
暫無

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

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