繁体   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