Add element to a JSON file?

Question:

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?

Asked By: Biribu

||

Answers:

You can do this.

data[0]['f'] = var
Answered By: Jayanth Koushik

alternatively you can do

iter(data).next()['f'] = var
Answered By: Vincent Claes

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.

Answered By: Johan Sulaiman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.