简体   繁体   中英

How to fix this error json.decoder.JSONDecodeError: Python

could someone tell me please why this code works only one time and in the second time i get an error My code:

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'] )

in the second time execution i got this error :

  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)

its not the same Issue as this link bellow, because i don't have two dictionnaries{}{}: Python json.loads shows ValueError: Extra data

Reading your code, I suspect your true intent is:

  • test.json should only ever contain exactly one dictionary.
  • That dictionary should have a key, "test_device", containing a list.
  • Every time the program executes, a new element should be appended to that list.

If this is the case, then you should not be creating a new dictionary every time and appending it to the file. You should write a single dictionary which completely overwrites the older versions of itself.

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'] )

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM