【问题标题】:Get the elements from nested JSON with Python using json lib使用 json lib 使用 Python 从嵌套 JSON 中获取元素
【发布时间】:2017-11-12 18:32:46
【问题描述】:

我想用“BoxDet”名称列出“BoxDet”中的所有元素。目的是以这种方式列出它: BoxDet : ABC ...

我的 JSON 的一小部分:

{
   "id":1,
   "name":"BoxH",
   "readOnly":true,
   "children":[
      {
         "id":100,
         "name":"Box1",
         "readOnly":true,
         "children":[
            {
               "id":1003,
               "name":"Box2",
               "children":[
                  {
                     "id":1019,
                     "name":"BoxDet",
                     "Ids":[
                        "ABC",
                        "ABC2",
                        "DEF2",
                        "DEFHD",
                        "LKK"
                        ]
                    }
                ]
            }
        ]
    }
    ]
}

我的问题才刚刚开始,我只是不能像第一个 {} 那样深入。 我的代码...

output_json = json.load(open('root.json'))
for first in output_json:
    print first
    for second in first:
        print second

...返回给我类似的东西:

readOnly
r
e
a
d
O
n
l
y
children
c
h
i
l
d
r
e
n

... 以此类推。我什至无法深入到 Box1,更不用说 Box2。我正在使用 Python 2.7

【问题讨论】:

    标签: python json


    【解决方案1】:

    为此,您需要一个树搜索算法:

    def locateByName(e,name):
        if e.get('name',None) == name:
            return e
    
        for child in e.get('children',[]):
            result = locateByName(child,name)
            if result is not None:
                return result
    
        return None
    

    现在你可以使用这个递归函数来定位你想要的元素:

    node = locateByName(output_json, 'BoxDet')
    print node['name'],node['Ids']
    

    【讨论】:

    • 嗨亚伦,@Aaron Digulla,还有一个问题。你的解决方案对我很有魅力。我现在正在尝试更改您的代码以向我提供结果,而不是 Id,而是“名称”值本身。 [pastebin.com/MDPv0PND] 这是我的 json,我想提取 SUB、SUBSUB 和 NAME,当使用准 for 链时,我无法回到层次结构中来获取 SUBSUB2...你能不能把我放在正确的轨道?
    • 请提出一个新问题。
    • @AaronDigulla,为什么需要在 for 循环中保护 return result?您不能只返回结果并在最后省略return None 吗?
    • @Chielt 如果没有守卫,它只会考虑第一个孩子。
    【解决方案2】:

    当您尝试在 dict 上使用 for 循环时,没有任何特殊考虑,您只能从 dict 中获取键。那就是:

    >>> my_dict = {'foo': 'bar', 'baz':'quux'}
    >>> list(my_dict)
    ['foo', 'baz']
    >>> for x in my_dict:
    ...     print repr(x)    
    'foo'
    'baz'
    

    最常用的做法是使用dict.iteritems()(在python 3中只是dict.items()

    >>> for x in my_dict.iteritems():
    ...     print repr(x)
    ('foo', 'bar')
    ('baz', 'quux')
    

    或者您可以自己获取密钥的值:

    >>> for x in my_dict:
    ...     print repr(x), repr(my_dict[x])    
    'foo' 'bar'
    'baz' 'quux'
    

    【讨论】:

      【解决方案3】:

      如果您想遍历实体的子实体,您可以执行以下操作:

      for children in output_json["children"]:
          #Going down to ID: 100 level
          for grandchildren in children["children"]:
              #Going down to ID: 1003 level
              for grandgrandchildren in grandchildren["children"]:
                  #Going down to ID: 1019 level
                  if grandgrandchildren["name"] == "BoxDet":
                      return "BoxDet" + " ".join(grandgrandchildren["Ids"])
      

      并不是说 json 模块中涉及的数据结构或多或少像经典字典一样,您可以通过键访问值:

      my_dict[key] = value
      

      【讨论】:

      • 当您在字典上使用 for-in 时,它会迭代字典内的所有键。 "字典中的键"
      【解决方案4】:

      试试这样:

      output_json = json.load(open('root.json'))
      if "children" in output_json:
        children = output_json["children"]
        if "children" in children:
          children1 = children["children"]
          if "children" in children1:
            children2 = children1["children"]
            if "name" in children2:
              name = children2["name"]
            if "Ids" in children2:
              ids = children2["Ids"]
            print name, ids
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-13
        • 1970-01-01
        • 1970-01-01
        • 2016-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-13
        相关资源
        最近更新 更多