简体   繁体   中英

Adding element to Json list (Python)

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.

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"))

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)

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