Reputation: 41
So I'm struggling on adding an element to a json list that's saved on my machine. What I'm trying to is the json will update with the user's typed message. However I'm getting the error of "JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
with open(JSON_FILE, "r+") as data_file:
data = json.load(data_file)
data[0]['test'].append(enteredString)
json.dump(data, data_file)
Here is the Json I'm trying to update.
{"test": [
"test 1",
"test 2"
]}
I want it so that the new saved json file will be.
{"test": [
"test 1",
"test 2",
"New String"
]}
I can't figure out what I'm doing wrong, any help would be appreciated.
Upvotes: 2
Views: 3295
Reputation: 71
There are 2 problems in your code:
1) To reference the list, use data['test'] -- data['test'][0] is the first 't' in 'test 1'
2) To overwrite the output file, you need to close the file first and reopen it. As written, the code would append to the JSON_FILE.
Here's the corrected code:
data = json.load(open(JSON_FILE, "rb"))
data['test'].append(enteredString)
json.dump(data, open(JSON_FILE, "wb"))
Upvotes: 2
Reputation: 16908
It looks like you need to remove the [0] indexing operation from line 3...your JSON is an object at its top-level, and not a list. So you shouldn't need to grab the element at index "0" if there is no index 0.
with open(JSON_FILE, "r+") as data_file:
data = json.load(data_file)
data['test'].append(enteredString)
json.dump(data, data_file)
Upvotes: 1