[python] Add element to a JSON file?

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?

This question is related to python json

The answer is


You can do this.

data[0]['f'] = var

One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

test_json = { "a": 1, "b": 2}

Once you do this, adding a json element only involves the following line:

test_json["c"] = 3

This will result in:

{'a': 1, 'b': 2, 'c': 3}

Afterwards, you can add that json back into an array or a list of that is desired.


alternatively you can do

iter(data).next()['f'] = var