So I have a file python_dictionary.json
which contains a dictionary which I want to append to without having to open each time. Let's say that python_dictionary.json
contains only:
{
key1: value`
}
and I want to add
new_dictionary=
{
key2:value2
}
Right now I am doing:
with open('python_dictionary.json','a') as file:
file.write(json.dumps(new_dictionary,indent=4))
This creates a dictionary as:
{
key1:value1
}
{
key2:value2
}
which is obviously not a real dictionary.
I am aware of this: Add values to existing json file without rewriting it
but this deals with adding a single entry, I want to do a json.dumps
Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.
Updating a JSON object in Python is as simple as using the built-in update() function from the json package we have imported. The update method is used to add a new key-value pair to the JSON string that we declared in our code.
To update JSON data in a table: Query and retrieve the JSON data from a JSON column. Modify the contents of the JSON column. To push the updated column value back into the table, issue the UPDATE SQL statement and specify the JSON2BSON function.
JSON at its top-level is a dictionary of attribute/value pairs, or key/value pairs as we've talked about dictionaries in this class. The values are numbers, strings, other dictionaries, and lists. Here is a simple example with just 4 attribute/value pairs.
Sounds like you want to load a dictionary from json, add new key values and write it back. If that's the case, you can do this:
with open('python_dictionary.json','r+') as f:
dic = json.load(f)
dic.update(new_dictionary)
json.dump(dic, f)
(mode is 'r+'
for reading and writing, not appending because you're re-writing the entire file)
If you want to do the append thing, along with json.dumps, I guess you'd have to remove the first {
from the json.dumps string before appending. Something like:
with open('python_dictionary.json','a') as f:
str = json.dumps(new_dictionary).replace('{', ',', 1)
f.seek(-2,2)
f.write(str)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With