代码之家  ›  专栏  ›  技术社区  ›  AutoTester213

遍历嵌套的JSON对象并存储值-python

  •  0
  • AutoTester213  · 技术社区  · 6 年前

    这是这个问题的后续行动。 Question

    这个问题也很相似,但不能解决我的问题 Question2

    我正试图解析一个嵌套的JSON来检查一个特定位置有多少子节点,我正试图检查 "children:" = None 和递增计数器,以检查为了得到最低的孩子,我需要下降多少个级别,或者 更有效的解决方案是:

    我需要把所有的儿童价值观都列成一个清单,并且一直到 “子项:”=无 .

    JSON对象可以增加子对象的数量,这样我们就可以有多个级别的子对象,如果我想嵌套列表并获取值,那么这些子对象可能会变得混乱,我如何动态地进行呢?

    {
        'locationId': 'location1',
        'name': 'Name',
        'type': 'Ward',
        'patientId': None,
        'children': [{
            'locationId': 'Child_location2',
            'name': 'Name',
            'type': 'Bed',
            'patientId': None,
            'children': [{
                'locationId': 'Child_Child_location3',
                'name': 'Name',
                'type': 'HospitalGroup',
                'patientId': None,
                'children': None
            }]
        }, {
            'locationId': 'location4',
            'name': 'Name',
            'type': 'Hospital',
            'patientId': None,
            'children': None
        }, {
            'locationId': 'location5',
            'name': 'Name',
            'type': 'Bed',
            'patientId': None,
            'children': None
        }, {
            'locationId': 'location6',
            'name': 'Name',
            'type': 'Bed',
            'patientId': None,
            'children': None
        }, {
            'locationId': 'location27',
            'name': 'Name',
            'type': 'Bed',
            'patientId': None,
            'children': None
        }]
    }
    

    我试着做这样的事

    import requests
    def Get_Child(URL, Name):
            headers = {
                'accept': 'text/plain',
            }
    
            response = requests.get(
                URL + Name,
                headers=headers)
            json_data = response.json()
            print (json_data)
            list = []
            for locationId in json_data['locationId']:
                list.append(locationId)
                for children in locationId['children']:
                    list.append(children)
    

    但这给了我以下的错误,

    for children in locationId['locationId']: TypeError: string indices must be integers
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   gold_cy    6 年前

    您的代码显示append,但您要求计数。如果我正确理解您的话,下面是获取此JSON中子级数量的递归方法:

    def get_children(body, c=1):
        if not body.get('children'):
            c += 1
        elif isinstance(body.get('children'), list):
                c += 1
                for subchild in body.get('children'):
                    c += 1
                    get_children(subchild, c)
        return c
    
    counts = get_children(your_json_blob)
    print(counts)
    >>> 7
    

    编辑:我故意不使用 if/else 因为我不知道你能不能有个孩子 dict 而不是 list 这意味着你需要额外的条件,但如果情况真的是这样的话,那就取决于你自己了。

        2
  •  0
  •   AutoTester213    6 年前

    我找到了解决问题的方法,

    下面的代码将获取所有子项并将它们附加到列表中

    class Children():
      def Get_All_Children(self,json_input, lookup_key):
          if isinstance(json_input, dict):
              for k, v in json_input.items():
                  if k == lookup_key:
                      yield v
                  else:
                      yield from self.Get_All_Children(v, lookup_key)
          elif isinstance(json_input, list):
              for item in json_input:
                  yield from self.Get_All_Children(item, lookup_key)
    
    
    for locations in self.Get_All_Children(self.json_data, 'locationId'):
        self.mylist.append(locations)