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
user391986
  • 29,536
  • 39
  • 126
  • 205
  • Note that the [JSON Validator](http://jsonlint.com/) has issues with your JSON. It validates if you remove the last two commas (see `json_string` in the answer by Pablo). – David Alber Nov 22 '11 at 01:59

1 Answers1

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)
Pablo
  • 8,644
  • 2
  • 39
  • 29
  • 3
    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](http://stackoverflow.com/questions/712791/json-and-simplejson-module-differences-in-python). – Tadeck Nov 22 '11 at 01:28