"string indices must be integers" error when parsing JSON

  json, python, python-3.x

I have the following JSON and I would like to extract all the email’s within it. The json is exported from AWS cognito and I have no control over how it is structured.

expected_value = """{
  "Users": [
    {
      "Username": "testUserName1",
      "Attributes": [
        {
          "Name": "testName1",
          "Value": "[email protected]"
        }
      ],
      "UserCreateDate": "2021-09-13T11:16:02.627000+01:00",
      "UserLastModifiedDate": "2021-09-13T11:16:02.627000+01:00",
      "Enabled": true,
      "UserStatus": "UNCONFIRMED"
    },
    {
      "Username": "testUsername2",
      "Attributes": [
        {
          "Name": "testEmail2",
          "Value": "[email protected]"
        }
      ],
      "UserCreateDate": "2021-02-19T11:52:52.465000+00:00",
      "UserLastModifiedDate": "2021-02-19T11:52:52.465000+00:00",
      "Enabled": true,
      "UserStatus": "UNCONFIRMED"
    }
  ]
}"""

I have the following code where I am feeding in the json for now as expected value:

def lambda_handler(event, context):
    data = json.dumps(expected_value)
    y = json.loads(data)
    email = y['Users'][0]['Attributes'][0]['Value']

But I get the following error:

{
  "errorMessage": "string indices must be integers",
  "errorType": "TypeError",
  "requestId": "622258cc-8248-4901-8a39-fc6e0a24229c",
  "stackTrace": [
    "  File "/var/task/lambda_function.py", line 145, in lambda_handlern    email = y['Users'][0]['Attributes'][0]['Value']n"
  ]
}

I can’t figure out what I am doing wrong.

As requested, a REPREX which still throws the error:

Source: Python-3x Questions

LEAVE A COMMENT