0

I have a python lambda function which receives posted data. The function looks a bit like this:

import json
import ....


def handle(event, context):

    if event["body"]:
        posted_data = json.loads(event["body"])
        print(posted_data)
        print(posted_data["email"])
        print(posted_data.get("email"))

The line print(posted_data) prints my json object like this:

{
    "tel": "078723646",
    "message": "jsd fljxdisfbv lskdjnildufv nlksjfg",
    "email": "[email protected]"
}

The line print(posted_data["email"]) gives me this error:
[ERROR] TypeError: string indices must be integers

The line print(posted_data.get("email") give this error:
[ERROR] AttributeError: 'str' object has no attribute 'get'

Yet, when I open a console, run python, and do this:

>>> obj = {"tel": "078276353", "message": "uisdjy df jdslfj lsdjf fb", "email": "[email protected]"}
>>> type(obj)

The response I get is: <class 'dict'> So, I'm a little confused as to whether it's a dictionary or a string.

What I need to do is to access each of the values in the object.
I tried this, but that had the effect of reversing the json.loads
I also looked here, but that did not assist. I checked this but it doesn't seem to be relevant to my case.

After a suggestion from @brunns I inserted print(type(posted_data)) after posted_data = json.loads(event["body"]) and discovered that posted_data is in fact a string.

I was expecting json.loads(event["body"]) to convert the json object to a python object. How do I go about retrieving the values in the object?

5
  • 1
    Try print(type(posted_data)) before the line which fails. Commented Apr 25, 2019 at 15:56
  • Thanks @brunns, it's a string <class 'str'>. So json.loads didn't convert it to a python object. I will amend my question. Commented Apr 25, 2019 at 16:03
  • Show us the output of repr(event["body"]). Commented Apr 25, 2019 at 16:09
  • repr(event["body"]) outputs '"{\\"tel\\": \\"0789374298347\\", \\"message\\": \\"kjsd bfkdjf vskdjfv df\\", \\"email\\": \\"[email protected]\\"}"' Commented Apr 25, 2019 at 16:23
  • 1
    It looks like the body has been converted to JSON twice, with the equivalent of body = json.dumps(json.dumps(data)). See what happens if you call json.loads() twice. If that fixes it, that means the the code posting the data should be fixed. Is it possible you're using something like jquery, and posting the data like json=JSON.stringify(data)? Some web libraries will automatically encode the JSON for you. Commented Apr 25, 2019 at 16:43

0

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.