I am trying to add an element to a json file in python but I am not able to do it.
This is what I tried untill now (with some variation which I deleted):
import json data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ] print 'DATA:', repr(data) var = 2.4 data.append({'f':var}) print 'JSON', json.dumps(data)
But, what I get is:
DATA: [{'a': 'A', 'c': 3.0, 'b': (2, 4)}] JSON [{"a": "A", "c": 3.0, "b": [2, 4]}, {"f": 2.4}]
Which is fine because I also need this to add a new row instead an element but I want to get something like this:
[{'a': 'A', 'c': 3.0, 'b': (2, 4), "f":2.4}]
How should I add the new element?
In order to add Key/value pair to a JSON object, Either we use dot notation or square bracket notation. Both methods are widely accepted. Example 1: This example adds {“prop_4” : “val_4”} to the GFG_p object by using dot notation.
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.
First you would need to convert it to a JavaScript Object. Once it is an Object, then you can just use dot notation into the object to change the values that you want. Lastly, you would convert that JavaScript Object back into a JSON string.
You can do this.
data[0]['f'] = var
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