【问题标题】:How to extract the attributes from a node in a json dictionary?如何从json字典中的节点中提取属性?
【发布时间】:2019-07-30 18:54:32
【问题描述】:

我有一本包含以下 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
  }
}

我有以下问题,目前对如何解决此问题感到非常困惑。 当我请求“TeamA”或“TeamSub”等“键”时,我希望能够解析该字典并获得“@oid”值和相应“@oid”的连接。

我有一个接收 gettheiDLevelConcatoid(myjsonDictionary, key) 的函数。

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

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

预期的输出应该是“123.0.0.1.2”。注意 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".

我目前的实现:

def gettheiDLevelConcatoid(myjsonDictionary, key)
   for item in myjsonDictionary:
       if (item == key):
        #not sure what to do

我对如何为此实现通用方法或方法感到迷茫。

【问题讨论】:

  • 贴出你当前的函数体,你已经尝试过简单的遍历了吗?
  • 迷失了如何实现一个通用的方法或方法? - 从Teams的简单循环开始
  • @RomanPerekhrest 我查看了字典,但不确定如何访问这些属性。我不确定是否有简单的方法或内置函数可以简化遍历。添加了我现在拥有的代码。
  • key 的搜索深度有多大?
  • @RomanPerekhrest 请查看对问题所做的更新

标签: python json


【解决方案1】:

对特定键进行递归遍历:

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

【讨论】:

  • 是否可以使if k.startswith('Team'): 更通用,因为它可能是“团队”以外的其他字符串。
  • @LauraSmith,如果它与概念键名无关,那么您将不得不检查每个字典中的 '@oid''dataRequestList']['state'] 键,这更麻烦
  • 不确定你是否明白我的意思。在对 get_team_idlvel_oid_pair 的调用中,我可以通过 ```get_team_idlvel_oid_pair(myjsonDictionary, "TeamA") 而不是您建议的调用,然后遍历字典并查找“TeamA”并返回连接的“@oid " 上述问题中所述的值。
  • 我尝试按照上一条评论中所述的方法修改您的代码,但我无法访问嵌套节点并且只能访问外层节点
  • 如果您有更新,请告诉我。任意
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多