3

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

AhmyOhlin
  • 519
  • 4
  • 8
  • 18
  • 2
    Possible duplicate of [Python json.loads shows ValueError: Extra data](https://stackoverflow.com/questions/21058935/python-json-loads-shows-valueerror-extra-data) – Georgy Jan 05 '18 at 15:21
  • @Georgy your comment and your downvote doesn't bring me anything. i saw the link which your provided already. its not the same case. i don't have two dictionnaries. – AhmyOhlin Jan 05 '18 at 16:31
  • I didn't downvote – Georgy Jan 05 '18 at 16:34
  • 1
    But you _do_ have two dictionaries. You run your code once, and your file has one dictionary. You run your code a second time, and your file now has two dictionaries. – Kevin Jan 05 '18 at 16:43
  • 1
    Let's say your code starts working the way you want and you run it five times. What do you expect `json_data` to contain at that point? If you're thinking "a list of five dictionaries", then you can't get that just by writing five dictionaries to the file one at a time. You need to dump a list, not a dict. If you're thinking "a single dictionary", then you shouldn't be opening the file in "a" mode, since the old dictionaries will remain in the file, alongside the new one. Most likely you should be `load`ing the old dictionary, updating its values, and re-dumping it in "w" mode. – Kevin Jan 05 '18 at 17:00
  • 1
    Ok, I've come around on whether this post is a duplicate or not. While the error message is the same, and in fact the underlying cause is the same, the intent is probably not: the proposed dupe's OP _wanted_ a file with multiple consecutive dictionaries. But this posts' OP only wants one dict, and is merely creating multiple ones as a side-effect of their desired behavior. This matters because the solution "dump a list of dicts" won't solve the true underlying problem at hand here. – Kevin Jan 05 '18 at 17:14

1 Answers1

2

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
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • this is exactly what i want. i understand now from where the error is comming. I will update my code. Thank you so much for your help. – AhmyOhlin Jan 05 '18 at 17:17
  • I used actually the same sruct of this tutorial to get a correct form of json file, but i think in this Tutorial the code will be run only one time, this why it doesnt bring the same error which i had in my case above. http://stackabuse.com/reading-and-writing-json-to-a-file-in-python/ – AhmyOhlin Jan 05 '18 at 17:23