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
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With