【问题标题】:flatten nested json with json_normalize使用 json_normalize 展平嵌套的 json
【发布时间】:2019-02-12 00:54:54
【问题描述】:

我有一个这样的嵌套 json:

{  
  "Invalids":[  
  {  
     "Comments":"string",
     "InputRequest":{  
        "LinesInfo":[  
           {  
              "LastPipeLineStateIds":[  
                 0
              ],
              "CropId":0
           }
        ],
        "Crop":"string",
        "Year":"string"
     }
  },
  {  
     "Comments":"string",
     "InputRequest":{  
        "LinesInfo":[  
           {  
              "LastPipeLineStateIds":[  
                 0
              ],
              "CropId":0
           }
        ],
        "name":"string",
        "number":"string"
     }
  }
],
"LinesResponse":{  },
"ErrorInfo":"string"
}

如果 'Invalids' 不为空,我想获得一个包含 'name' 和 'number' 的表。我正在这样做:

a = json_normalize(data['Invalid'])

但输出有前缀,如:'InputRequest.name',这是我不想要的。如何获得“姓名”和“号码”的干净列表(以“cmets”作为元数据)?

【问题讨论】:

    标签: python json pandas normalize


    【解决方案1】:

    你可以这样管理它:

    nested_json = {  
        "Invalids": [  
            ...
         ]
    }
    
    def get_names_and_numbers(json_data):
        """
        Return names and numbers in json_data.
        """
        names_list = []
        numbers_list= []
    
        Invalids = nested_json['Invalids']
        if Invalids: # *note that Invalids is a list an this referers to its lenght*
            names_list.append(Invalids[1]['InputRequest']['name'])
            numbers_list.append(Invalids[1]['InputRequest']['number'])
            return names_list, numbers_list
        else:
             return None, None
    
    names, numbers = get_names_and_numbers(nested_json)
    

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 2017-09-18
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 2021-09-19
      • 2019-06-12
      相关资源
      最近更新 更多