问题
How to change Values in JSON by using Python in any of the nodes (value1, value2, value3, value4, value5, value6, value7):
{
"key1": "value1",
"level2": {
"key2": "value2",
"key3": "value3",
"level3": [
{
"key4": "value4",
"level5": [
{
"key5": "value5",
"key6": "value6"
}
],
"key7": "value7"
}
]
}
}
After changing e.g. Value6 with some other value - I would like to print that new JSON in a nice print format (same as above).
Thanks.
回答1:
You'll want to first convert the string to a python dictionary, then manipulate the dictionary, and finally dump the dictionary back to a string. Here's a simple example:
import json
json_string = '{"foo": "bar"}'
json_dict = json.loads(json_string)
json_dict["foo"] = "baz"
print json.dumps(json_dict, indent=4)
来源:https://stackoverflow.com/questions/48308356/python-change-json-values-and-pretty-print