如何修复此错误json.decoder.JSONDecodeError:Python

时间:2018-01-05 15:13:48

标签: python json

有人可以告诉我为什么这段代码只工作一次,第二次我得到错误 我的代码:

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 shows ValueError: Extra data

1 个答案:

答案 0 :(得分:1)

阅读你的代码,我怀疑你的真实意图是:

  • 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