8

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
1
  • Note that the JSON Validator has issues with your JSON. It validates if you remove the last two commas (see json_string in the answer by Pablo). Commented Nov 22, 2011 at 1:59

1 Answer 1

17

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)
Sign up to request clarification or add additional context in comments.

1 Comment

One additional thing about json module: for earlier versions simplejson should be available if json is not. By doing import simplejson as json (import json if ImportError was caught) one can gain compatibility with older versions and possibly profit from performance gains (simplejson is said to be updated more frequently). Both modules have the same interface, thus they are used in the same manner. See more in this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.