我有一个json文件,当使用json.loads()加载到python中时,它就变成了一个dictionary。json数据是一个nested dictionary,它可以在另一个'groups'密钥中包含一个'groups'密钥。'groups'密钥中的值是'name'密钥和'properties'密钥。
每个'properties'密钥都有唯一的'name'和'value'密钥。
我的目标是搜索'groups'密钥,其'name'密钥的值为"SportCar",其properties密钥的name密钥的值为"BMW",并且仅当满足这些条件时,才将'data'密钥从'data':value1更新为'data':value2。
下面是json的一个示例。
{
"groups": [
{
"name": "SportCar",
"properties": [
{
"name": "BMW",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value1"
}
},
{
"name": "Audi",
"value": {
"type": "Boolean",
"data": true
}
}
],
"groups": [
{
"name": "Trucks",
"properties": [
{
"name": "Volvo",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value1"
}
}
]
}
]
},
{
"name": "MotorCycle",
"properties": [
{
"name": "Yamaha",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value1"
}
}
],
"groups": [
{
"name": "Speeders",
"properties": [
{
"name": "prop2",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value1"
}
}
]
}
]
}
]
}上面的json包含在myjson22.json中。这是我到目前为止尝试过的:
import json
from pprint import pprint
json_data=open('myjson22.json', 'r')
data = json.load(json_data)
#print(data)
def get_recursively(search_dict, field):
"""
To read the json data as type dict and search all 'groups' keys for the 'name' key value value provided.
"""
fields_found = []
for key, value in search_dict.items():
if key == field:
fields_found.append(value)
elif isinstance(value, dict):
results = get_recursively(value, field)
for result in results:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, field)
for another_result in more_results:
fields_found.append(another_result)
return fields_found
get_recursively(data, ["properties"][0])输出结果是:
[[{'name': 'BMW',
'value': {'data': 'value1', 'encoding': 'utf-8', 'type': 'String'}},
{'name': 'Audi', 'value': {'data': True, 'type': 'Boolean'}}],
[{'name': 'Volvo',
'value': {'data': 'value1', 'encoding': 'utf-8', 'type': 'String'}}],
[{'name': 'Yamaha',
'value': {'data': 'value1', 'encoding': 'utf-8', 'type': 'String'}}],
[{'name': 'prop2',
'value': {'data': 'value1', 'encoding': 'utf-8', 'type': 'String'}}]]发布于 2016-08-09 06:11:54
实现这种递归解决方案的一种方法是回溯。当在根键中找不到嵌套的'groups'键时,'name'键值将与groups_name参数匹配,在本例中该参数为'SportCar‘。如果满足此条件,请检查相同'groups'键中的值(即'SportCar‘键) 'properties'键,并将其'name'键值与properties_name参数(在本例中为'BMW’)进行匹配。如果第二个条件也为真,则根据需要更新同一个'properties'键中的'data'键值,否则返回(用于回溯)。
import json
json_data = open('myjson22.json', 'r')
data = json.load(json_data)
def get_recursively( myJson, groups_name, properties_name, value2):
if 'groups' in myJson.keys():
# As there are multiple values inside 'groups' key
for jsonInsideGroupsKey in myJson['groups']:
get_recursively( jsonInsideGroupsKey, groups_name, properties_name, value2)
if 'name' in myJson.keys():
# check for groups name
if myJson['name'] == groups_name:
# check for properties name
if myJson['properties'][0]['name'] == properties_name:
# Update value. The changes will persist as we backtrack because
# we are making the update at the original memory location
# and not on a copy. For more info see deep and shallow copy.
myJson['properties'][0]['value']['data'] = value2
return
get_recursively(data,'SportCar','BMW','changedValue1')
get_recursively(data,'Speeders','prop2','changedValue2')
print data我的输出:
{u‘’groups‘:[{u’‘name’:u‘’SportCar‘,u’‘groups’:[{u‘’name‘:u’‘Trucks’,u‘’properties‘:{u’‘name’:u‘’Volvo‘,u’‘value’:{u‘’data‘:u'value1',u’‘type’:u‘’String‘,u’‘encoding’:u‘’utf 8‘}}]],u’‘properties’:{u‘’name‘:u’‘BMW’,u‘’value‘:{u’‘data’:'changedValue1',U‘类型’:u‘字符串’,u‘编码’:u‘’utf 8‘}},{u’‘name’:u‘’Audi‘,u’‘value’:{u‘’data‘:True,u’‘type’:u‘’Boolean‘},{u’‘name’:u‘’MotorCycle‘,u’‘groups’:[{u‘’name‘:u’‘Speeders’,u‘’properties‘:{u’‘name’:u'prop2',u‘’value‘:{u’‘data’:'changedValue2',U‘类型’:u‘字符串’,u‘编码’:u‘’utf 8‘}],u’‘properties’:{u‘’name‘:u’‘Yamaha’,u‘’value‘:{u’‘data’:u'value1',u‘’type‘:u’‘String’,u‘编码’:u‘’utf 8‘}
经过美化后,它看起来会像这样:
{
"groups": [
{
"name": "SportCar",
"properties": [
{
"name": "BMW",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "ChangedValue1"
}
},
{
"name": "Audi",
"value": {
"type": "Boolean",
"data": true
}
}
],
"groups": [
{
"name": "Trucks",
"properties": [
{
"name": "Volvo",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value1"
}
}
]
}
]
},
{
"name": "MotorCycle",
"properties": [
{
"name": "Yamaha",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "value1"
}
}
],
"groups": [
{
"name": "Speeders",
"properties": [
{
"name": "prop2",
"value": {
"type": "String",
"encoding": "utf-8",
"data": "ChangedValue2"
}
}
]
}
]
}
]
}https://stackoverflow.com/questions/38837507
复制相似问题