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?