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?
print(type(posted_data))before the line which fails.<class 'str'>. Sojson.loadsdidn't convert it to a python object. I will amend my question.repr(event["body"]).'"{\\"tel\\": \\"0789374298347\\", \\"message\\": \\"kjsd bfkdjf vskdjfv df\\", \\"email\\": \\"[email protected]\\"}"'body = json.dumps(json.dumps(data)). See what happens if you calljson.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 likejson=JSON.stringify(data)? Some web libraries will automatically encode the JSON for you.