如何从json字典中的节点提取属性? [英] How to extract the attributes from a node in a json dictionary?

查看:53
本文介绍了如何从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

这篇关于如何从json字典中的节点提取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆