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": "my@selg.om"
}

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": "tetet@gdgdg.lo"}
>>> 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?

Jez D
  • 1,461
  • 2
  • 25
  • 52
  • 1
    Try `print(type(posted_data))` before the line which fails. – brunns Apr 25 '19 at 15:56
  • Thanks @brunns, it's a string ``. So `json.loads` didn't convert it to a python object. I will amend my question. – Jez D Apr 25 '19 at 16:03
  • Show us the output of `repr(event["body"])`. – John Gordon Apr 25 '19 at 16:09
  • repr(event["body"]) outputs `'"{\\"tel\\": \\"0789374298347\\", \\"message\\": \\"kjsd bfkdjf vskdjfv df\\", \\"email\\": \\"gfgfg@hhh.cd\\"}"'` – Jez D Apr 25 '19 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. – almiki Apr 25 '19 at 16:43

0 Answers0