如何从json字典中的节点提取属性?
我有一个包含以下json元素的字典.
I have a dictionary which contains the following json elements.
myjsonDictionary = \
{
"Teams": {
"TeamA": {
"@oid": "123.0.0.1",
"dataRequestList": {
"state": {
"@default": "0",
"@oid": "2"
}
},
"TeamSub": {
"@oid": "3",
"dataRequestList": {
"state": {
"@default": "0",
"@oid": "2"
}
}
}
},
# ....many nested layers
}
}
我遇到以下问题,目前对如何解决此问题非常困惑. 我希望能够解析此字典并在请求键"(例如"TeamA"或"TeamSub")时获得"@oid"值和相应的"@oid"的串联.
I have the following issue and am currently very confused on how to solve this problem. I want to be able to parse this dictionary and get the concatenation of the "@oid" value and the respective "@oid" when I request the "key" such as "TeamA" or "TeamSub".
我有一个接收gettheiDLevelConcatoid(myjsonDictionary,key)的函数.
I have a function which takes in the gettheiDLevelConcatoid(myjsonDictionary, key).
我可以这样调用此函数:
I can call this function like this:
gettheiDLevelConcatoid(myjsonDictionary, key) where "key" is like "TeamA"
,预期输出应为"123.0.0.1.2".请注意123.0.0.1所附的2.
And the expected output should be "123.0.0.1.2". Note the 2 appended to the 123.0.0.1.
gettheiDLevelConcatoid(myjsonDictionary, key) where "key" is like TeamSub
Output is "123.0.0.1.3.2". Note the "3.2" added to the "123.0.0.1".
我当前的实现方式:
def gettheiDLevelConcatoid(myjsonDictionary, key)
for item in myjsonDictionary:
if (item == key):
#not sure what to do
我对如何实现通用方法或方法感到迷茫.
I am so lost on how to implement a generic method or approach for this.
具有对特定键的递归遍历:
With recursive traversal for specific keys:
def get_team_idlvel_oid_pair(d, search_key):
for k, v in d.items():
if k.startswith('Team'):
if k == search_key:
return '{}{}.{}'.format(d['@oid'] + '.' if '@oid' in d else '',
v['@oid'], v['dataRequestList']['state']['@oid'])
elif any(k.startswith('Team') for k_ in v):
return get_team_idlvel_oid_pair(v, search_key)
print(get_team_idlvel_oid_pair(myjsonDictionary['Teams'], 'TeamA'))
print(get_team_idlvel_oid_pair(myjsonDictionary['Teams'], 'TeamSub'))
示例输出:
123.0.0.1.2
123.0.0.1.3.2