在Python中解析嵌套JSON信息

arknldoa  于 2022-11-19  发布在  Python
关注(0)|答案(2)|浏览(159)

从下面的JSON字符串中,我尝试提取所有的waiverId:

data = 
{
  "version": 4,
  "id": "(requestId)",
  "ts": "2022-11-14T20:24:50+00:00",
  "type": "checkins",
  "checkins": {
    "fromDts": "2022-07-01",
    "toDts": "2022-07-02",
    "moreCheckins": true,
    "checkins": [
      {
        "date": "2022-07-01 15:18:09",
        "waiverId": "(id1)",
        "position": 0,
        "firstName": "(first name)",
        "lastName": "(last name)"
      },
      {
        "date": "2022-07-01 15:19:10",
        "waiverId": "(id2)",
        "position": 0,
        "firstName": "(first name)",
        "lastName": "(last name)"
      }
    ]
  }
}

我已尝试以下方法:

for checkins in data['checkins']:
    print(checkins)

它只给出:

fromDts
toDts
moreCheckins
checkins

我只需要一份清单:标识1标识2

5gfr0r5j

5gfr0r5j1#

您需要从'checkins'中提取checkins的列表,如下所示:

for checkins in data['checkins']['checkins']:
    print(checkins)

第一个键checkins返回一个包含键checkinsdict值,其中包含所需的dict的数据列表。

ocebsuys

ocebsuys2#

假设:

1.您处理的字典已经是python可以处理的形式(所以'true'变成了'True')。

  1. response.json(),您最好指定您要执行的操作。我将直接将给定的变量视为正确形式的字典。
    只需按照@user99999的指示遍历 Dataframe ,并将您要查找的元素添加到列表中:
data = {
  "version": 4,
  "id": "(requestId)",
  "ts": "2022-11-14T20:24:50+00:00",
  "type": "checkins",
  "checkins": {
    "fromDts": "2022-07-01",
    "toDts": "2022-07-02",
    "moreCheckins": True,
    "checkins": [
      {
        "date": "2022-07-01 15:18:09",
        "waiverId": "(id1)",
        "position": 0,
        "firstName": "(first name)",
        "lastName": "(last name)"
      },
      {
        "date": "2022-07-01 15:19:10",
        "waiverId": "(id2)",
        "position": 0,
        "firstName": "(first name)",
        "lastName": "(last name)"
      }
    ]
  }
}

waiverIds = []
for checkins in data['checkins']['checkins']:
    waiverIds.append(checkins['waiverId'])

print(waiverIds)

输出将为:

['(id1)', '(id2)']

相关问题