如何逐级解嵌 JSON

How to unnest JSON with levels upon levels

提问人:CartHack-3421 提问时间:11/18/2022 最后编辑:CartHack-3421 更新时间:11/18/2022 访问量:77

问:

我正在尝试取消嵌套 json 文件。JSON 在字典列表中有多个字典列表。我正在尝试将其中的所有内容展平并将其转换为数据帧。它看起来像这样:

{
 "Result": [
   {
     "OptionalColumns": {
       "optionalColumnName": "Joe Blogs"
     },
     "fieldOne": "some string",
     "fieldtwo": "some more string",
     "fieldthree": "even more string",
     "secondList": [
       {
         "secondListFieldOne": "value",
         "secondListFieldTwo": 0,
         "secondListFieldThree": true
       },
       {
         "secondListFieldOne": "value",
         "secondListFieldTwo": 0,
         "secondListFieldThree": true
       }
     ],
     "anotherField": "string value",
     "thirdList": [
       {
         "thirdListFieldOne": "string",
         "thirdListFieldTwo": "string"
       }
     ],
     "someNumberValue": 1
   },
   {
     "OptionalColumns": {
       "optionalColumnName": "Joe Blogs"
     },
     "fieldOne": "some string",
     "fieldtwo": "some more string",
     "fieldthree": "even more string",
     "secondList": [
       {
         "secondListFieldOne": "value",
         "secondListFieldTwo": 0,
         "secondListFieldThree": true
       },
       {
         "secondListFieldOne": "value",
         "secondListFieldTwo": 0,
         "secondListFieldThree": true
       }
     ],
     "anotherField": "string value",
     "thirdList": [
       {
         "thirdListFieldOne": "string",
         "thirdListFieldTwo": "string"
       }
      ],
      "someNumberValue": 1
    }
  ],
  "Message": null,
  "Errors": []
}

我正在使用以下方法来取消嵌套。我知道这适用于一个巢穴,甚至两个巢穴,但是我一辈子都无法让它起作用。帮助。

with open('data/my_file.json','r') as f:
    json_data = json.loads(f.read())

df_unnested_list = pd.json_normalize(json_data, 'Result')

尝试取消嵌套字典列表时:

pd.json_normalize(data, "field", ["fieldTwo", "nestFieldOne"])
python 数组 json 嵌套列表 unnest

评论


答:

0赞 JCart15 11/18/2022 #1

这将是您之前用另一个字典发布它的方式。真的很简单。

pd.json_normalize(data, “thirdList”, [“OptionalColumns”, “optionalColumnName”],”fieldOne”, “fieldTwo”, “fieldThree”, [“secondList”, “secondListDictOneFieldOne”,”secondListDictTwoFieldOne”], “anotherField”, “someNumberValue”)

评论

0赞 CartHack-3421 11/18/2022
我试过了这个,不幸的是它没有用。