解析嵌套 JSON 对象中的对象

问题描述 投票:0回答:1

我正在尝试解析 json 响应对象以获取每条记录的 hashID (objectiveHash),但遇到错误。

这是错误。

TypeError: string indices must be integers

这里是response.JSON的片段供参考:

{
  "Response": {
    "records": {
      "data": {
        "featuredRecordHashes": [
          3241995275,
          3623956709,
          1257350901
        ],
        "records": {
          "18302305": {
            "state": 0,
            "objectives": [
              {
                "objectiveHash": 836033085,
                "progress": 1,
                "completionValue": 1,
                "complete": true,
                "visible": true
              }
            ],
            "intervalsRedeemedCount": 0
          },
          "100144154": {
            "state": 4,
            "objectives": [
              {
                "objectiveHash": 3797031509,
                "progress": 89,
                "completionValue": 100,
                "complete": false,
                "visible": true
              }
            ],
            "intervalsRedeemedCount": 0,
            "rewardVisibilty": [
              true,
              true
            ]
          }
...

这是相关代码。

json_response = response.json()
        for record in json_response['Response']['records']['data']['records']:
            myRecord = record['objectives']
            for tst in myRecord:
                hashID = str(tst['objectiveHash'])

根据一些研究,问题似乎是 myRecords 变量被视为字符串而不是对象或列表。因此,当我尝试解析它时,我收到错误,因为无法解析字符串。我不知道如何将该值作为可解析对象获取。

python json parsing
1个回答
0
投票

您的 for 循环正在获取分配给记录变量的键。记录是一本字典,迭代字典通常会得到键。

如果您想要这些值,请将 .values() 添加到 json_response['Response']['records']['data']['records'] 行的末尾。

如果您想同时拥有键和值,请修改代码以具有以下内容:

for key, record in json_response['Response']['records']['data']['records'].items():
© www.soinside.com 2019 - 2024. All rights reserved.