How do I insert data into a json list with python?

Viewed 38

I want to add a value to a json list with python. The json file looks like this:

{
    "values": [323123]
}

The python code looks like this:

import json

#any number
id = 1234

with open("values.json", "r+") as file:
    data = json.load(file)
    change = data["values"].append(id)
    json.dump(change, file)

and i want to make it look like this:

{
    "values": [323123, 1234]
}

But the code results in this:

{
    "values": [323123]
}null
2 Answers

Just read the file (not r+ which is read/write), make the change, then open the file for writing and write it. This will overwrite the original file instead of appending to it.

Note that .append returns None and modifies the list in-place, so assigning to change doesn't work.

Here's the correct code:

import json

#any number
id = 1234

with open("values.json") as file:
    data = json.load(file)

data["values"].append(id)

with open("values.json", "w") as file:
    json.dump(data, file)

When using json.dump(), you must dump the entire JSON data into the file; not just the change. Here is the code:

import json

#any number
id = 1234

with open("values.json", "r+") as file:
    data = json.load(file)
    data["filter"].append(id)
    json.dump(data, file)
Related