Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to a JSON file?

Tags:

python

json

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?

like image 414
Biribu Avatar asked Mar 10 '14 09:03

Biribu


People also ask

How do you push an element into a JSON object?

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.

How do I update an existing JSON file in Python?

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.

How do I change the value of a JSON file?

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.


1 Answers

You can do this.

data[0]['f'] = var 
like image 99
Jayanth Koushik Avatar answered Sep 20 '22 21:09

Jayanth Koushik