如何从json字典中的节点提取属性?

2024-06-26 14:25:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下json元素的字典。你知道吗

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
  }
}

我有以下问题,目前非常困惑如何解决这个问题。 我希望能够解析这个字典,并在请求“key”(如“TeamA”或“TeamSub”)时获得“@oid”值和相应的“@oid”的串联。你知道吗

我有一个函数,它接受gettheiDLevelConcatoid(myjsonDictionary,key)。你知道吗

我可以这样调用这个函数:

gettheiDLevelConcatoid(myjsonDictionary, key) where "key" is like "TeamA"

预期输出应为“123.0.0.1.2”。请注意123.0.0.1中附加的2。你知道吗

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

我对如何实现一个通用的方法或方法非常迷茫。你知道吗


Tags: thekey函数default字典iswherelike
1条回答
网友
1楼 · 发布于 2024-06-26 14:25:22

使用特定键的递归遍历:

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

相关问题 更多 >