cosmos-1905-14
cosmos-1905-14

Reputation: 1333

How to parse nested JSON in python

I'm struggling to access some values in this nested json in python.

How can I access this ['Records'][0]['s3']['bucket']['name'] ? I did search a lot to find a simple python snippet, but no luck. Thanks in advance!

{
  "Records": [
    {
      "eventName": "xxxxxxx",
      "userIdentity": {
        "principalId": "AWS:XXXXXXXXXXXXXX"
      },
      "requestParameters": {
        "sourceIPAddress": "XX.XX.XX.XX"
      },
      "responseElements": {
        "x-amz-request-id": "8CXXXXXXXXXXHRQX",
        "x-amz-id-2": "doZ3+gxxxxxxx"
      },
      "s3": {
        "s3SchemaVersion": "1.0",
        "configurationId": "X-Event",
        "bucket": {
          "name": "bucket-name",
          "ownerIdentity": {
            "principalId": "xxxxxxx"
          },
          "arn": "arn:aws:s3:::bucket-name"
        },
        "object": {
          "key": "object.png",
          "sequencer": "0060XXXXXXX75X"
        }
      }
    }
  ]
}

Upvotes: 0

Views: 5801

Answers (2)

mochsner
mochsner

Reputation: 325

Have you tried running your example? If you're loading the json from elsewhere, you'd need to convert it to this native dictionary object using the json library (as mentioned by others, json.loads(data))

kv = {
  "Records": [
    {
      "eventName": "xxxxxxx",
      "userIdentity": {
        "principalId": "AWS:XXXXXXXXXXXXXX"
      },
      "requestParameters": {
        "sourceIPAddress": "XX.XX.XX.XX"
      },
      "responseElements": {
        "x-amz-request-id": "8CXXXXXXXXXXHRQX",
        "x-amz-id-2": "doZ3+gxxxxxxx"
      },
      "s3": {
        "s3SchemaVersion": "1.0",
        "configurationId": "X-Event",
        "bucket": {
          "name": "bucket-name",
          "ownerIdentity": {
            "principalId": "xxxxxxx"
          },
          "arn": "arn:aws:s3:::bucket-name"
        },
        "object": {
          "key": "object.png",
          "sequencer": "0060XXXXXXX75X"
        }
      }
    }
  ]
}

print("RESULT:",kv['Records'][0]['s3']['bucket']['name'])

RESULT: bucket-name

Upvotes: 0

Supreme1707
Supreme1707

Reputation: 178

Since this is a string, use the json.loads method from the inbuilt JSON library.

import json

json_string = # your json string
parsed_string = json.loads(json_string)
print(parsed_string) # it will be a python dict
print(parsed_string['Records'][0]['s3']['bucket']['name']) # prints the string

Upvotes: 2

Related Questions