0

I am not able to access the data from the event in the python function

I am trying to get the name from the JSON

def handler(event, context):
     
    resp =  event
    user_name = resp['body']['user']['name']

but I get the following error

ERROR] TypeError: string indices must be integers
Traceback (most recent call last):
  File "/var/task/index.py", line 28, in handler
    user_name = resp['body']['user']['name']
4
  • maybe resp is already the body. try using resp['repository']['name'] and tell me the result. Commented May 26, 2021 at 12:49
  • I get the same error Commented May 26, 2021 at 12:52
  • bring more code to the question. cant debug with just 2 lines of code. please learn to bring more details or bring more code. Commented May 26, 2021 at 12:53
  • I am just trying to execute these 2 lines of code, there nothing other than this Commented May 26, 2021 at 13:00

2 Answers 2

1

It seems that resp is of string type. load your response in JSON before accessing it.

import json
resp = json.loads(resp)
Sign up to request clarification or add additional context in comments.

5 Comments

I am getting a Type Error for the json.loads(resp) ``` TypeError: the JSON object must be str, bytes or bytearray, not dict ```
use json.load
It say AttributeError: 'dict' object has no attribute 'read'. when I use resp = json.load(event)
If I use json.dumps() for the above error I get the same error as in the top of my question TypeError: string indices must be integers
@AbilashJayanandan find out the type of resp by using type(resp)
0

The below solution worked for me. The event body should be retrieved first

import json

def handler(event, context):
     resp =  json.loads(event["body"])
     user_name = event['user']['name']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.