我正在使用一些复杂的JSON文件,我需要读取所有值并在它们遇到某个字符串时重命名它们。
问题是JSON文件在字典里面的列表中包含字典......非常疯狂。这是一个例子:
{
"key1": {
"subkey11": "KeepMe1",
"subkey12": "ChangeMe2"
},
"key2": [],
"key3": [],
"key4": [
{
"subkey41": "ChangeMe41",
"subkey42": "KeepMe42",
"subkey43": "ChangeMe43",
"subkey44": [
{
"subkey441": "ChangeMe441",
"subkey442": "KeepMe442"
}
]
}
]
}
我如何递归地读取所有内容以获取值并在需要时重命名它们?
我对此感到非常疯狂。提前谢谢!
答案 0 :(得分:0)
如果你将json字符串转换为python dict对象会更容易。
import json
data = """
{
"key1": {
"subkey11": "KeepMe1",
"subkey12": "ChangeMe2"
},
"key2": [],
"key3": [],
"key4": [
{
"subkey41": "ChangeMe41",
"subkey42": "KeepMe42",
"subkey43": "ChangeMe43",
"subkey44": [
{
"subkey441": "ChangeMe441",
"subkey442": "KeepMe442"
}
]
}
]
}
"""
print json.loads(data)
输出: -
{u'key3': [], u'key2': [], u'key1': {u'subkey11': u'KeepMe1', u'subkey12': u'ChangeMe2'}, u'key4': [{u'subkey44': [{u'subkey441': u'ChangeMe441', u'subkey442': u'KeepMe442'}], u'subkey43': u'ChangeMe43', u'subkey42': u'KeepMe42', u'subkey41': u'ChangeMe41'}]}