Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing json python

Tags:

python

json

How can I iterate through the following json file and if fa="cc.ee" then add a value inside fb?

  {
        "pk": 1, 
        "fa": "cc.ee", 
        "fb": {
            "fc": "", 
            "fd_id": "12345", 
        }
    }, 


#!/usr/bin/env python
import json,urllib
json_data=open("my.json")
data = json.load(json_data)
for entry in data:
    json.dumps(entry)
json_data.close()
exit
like image 772
user391986 Avatar asked Nov 22 '11 01:11

user391986


People also ask

How do I parse a JSON in Python?

If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.

How do you parse a JSON array in Python?

To parse a JSON file, use the json. load() paired method (without the "s"). In this Python Parse JSON example, we convert JSON containing a nested array into a Python object and read the data by name and index. Click Execute to run the Python Parse JSON example online and see result.

How do you parse JSON?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.


1 Answers

JSON objects behave like dictionaries. You can add a value by assigning to the new key like you would for a dictionary:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)
like image 65
Pablo Avatar answered Sep 22 '22 05:09

Pablo