简体   繁体   English

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

[英]How to extract the attributes from a node in a json dictionary?

I have a dictionary which contains the following json elements.我有一个包含以下 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
  }
}

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".当我请求诸如“TeamA”或“TeamSub”之类的“键”时,我希望能够解析这个字典并获得“@oid”值和相应“@oid”的连接。

I have a function which takes in the gettheiDLevelConcatoid(myjsonDictionary, key).我有一个接受 gettheiDLevelConcatoid(myjsonDictionary, key) 的函数。

I can call this function like this:我可以这样调用这个函数:

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

And the expected output should be "123.0.0.1.2".预期输出应为“123.0.0.1.2”。 Note the 2 appended to the 123.0.0.1.注意 2 附加到 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".

My current implementation:我目前的实现:

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'))

Sample output:示例输出:

123.0.0.1.2
123.0.0.1.3.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM