【问题标题】:create dataframe from specific node in json response从 json 响应中的特定节点创建数据框
【发布时间】:2021-10-31 14:18:29
【问题描述】:

我有以下 JSON 结构:

{
  "products": [
    {
      "id": 12121,
      "product": "hair",
      "tag":"now, later",
      "types": [
        {
          "product_id": 11111,
          "id": 22222
        }
      ],
      "options": [
        {
          "name": "Title"
        }
      ]
    },
    {
        "id": 1313131,
        "product": "pillow",
        "tag":"later, never",
        "types": [
          {
            "product_id": 33333,
            "id": 44444
          }
        ],
        "options": [
          {
            "name": "Title"
          }
        ]
    },
    {
        "id": 14141414,
        "product": "face",
        "tag":"now, never",
        "types": [
          {
            "product_id": 5555,
            "id": 7777
          }
        ],
        "options": [
          {
            "name": "Title"
          }
        ]
    }
  ]
}

我希望仅当 tag 列表显示“现在”时,才为 types 中找到的值创建一个数据框,预期输出:

    tag   product_id  id
0   now   11111       22222     
1   now   5555        7777

我希望得到一些指导,因为我还没有处理具有多个列表的 JSON 结构,以及如何根据查找 tag 内部的值来定位目标。任何提示将不胜感激。提前谢谢你。

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    用列表理解试试这个:

    >>> pd.DataFrame([{'tag': 'now', **i['types'][0]} for i in dct['products'] if 'now' in i['tag']])
       tag  product_id     id
    0  now       11111  22222
    1  now        5555   7777
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 2019-01-12
      相关资源
      最近更新 更多