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?
This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 25 days ago.
In Python I'm getting an error:
Exception: (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)
Given python code:
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
request = urllib2.Request (url +
'.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
response = urllib2.urlopen (request)
jsonStr = response.read()
return json.load(jsonStr)['data']['children']
What does this error mean and what did I do to cause it?
The problem is that for json.load you should pass a file like object with a read function defined. So either you use json.load(response) or json.loads(response.read()).
Ok, this is an old thread but.
I had a same issue, my problem was I used json.load instead of json.loads
This way, json has no problem with loading any kind of dictionary.
Official documentation
json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.
json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
You need to open the file first. This doesn't work:
json_file = json.load('test.json')
But this works:
f = open('test.json')
json_file = json.load(f)
If you get a python error like this:
AttributeError: 'str' object has no attribute 'some_method'
You probably poisoned your object accidentally by overwriting your object with a string.
How to reproduce this error in python with a few lines of code:
#!/usr/bin/env python
import json
def foobar(json):
msg = json.loads(json)
foobar('{"batman": "yes"}')
Run it, which prints:
AttributeError: 'str' object has no attribute 'loads'
But change the name of the variablename, and it works fine:
#!/usr/bin/env python
import json
def foobar(jsonstring):
msg = json.loads(jsonstring)
foobar('{"batman": "yes"}')
This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.
AttributeError("'str' object has no attribute 'read'",)
This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).
The error occurred here:
json.load(jsonStr)['data']['children']
Well, you aren't looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonStr, which currently names a string (which you created by calling .read on the response).
Solution: don't call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.
You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on http://docs.python.org .
Instead of json.load() use json.loads() and it would work:
ex:
import json
from json import dumps
strinjJson = '{"event_type": "affected_element_added"}'
data = json.loads(strinjJson)
print(data)
So, don't use json.load(data.read()) use json.loads(data.read()):
def findMailOfDev(fileName):
file=open(fileName,'r')
data=file.read();
data=json.loads(data)
return data['mail']
use json.loads() function , put the s after that ... just a mistake btw i just realized after i searched error
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
request = urllib2.Request (url +
'.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
response = urllib2.urlopen (request)
jsonStr = response.read()
return json.loads(jsonStr)['data']['children']
try this
Open the file as a text file first
json_data = open("data.json", "r")
Now load it to dict
dict_data = json.load(json_data)
If you need to convert string to json. Then use loads() method instead of load(). load() function uses to load data from a file so used loads() to convert string to json object.
j_obj = json.loads('["label" : "data"]')
I badly need your help. I am currently trying to pass a string value using flash but I am not sure if I got it correctly.
This is my code:
def first_view(request):
request.flash['message'] = 'Operation succeeded!'
return HttpResponseRedirect(reverse(second_view))
def second_view(request):
print request.flash['message']
request.flash.keep('message')
return HttpResponseRedirect(reverse(third_view))
I'd like to pass the message "Operation Succeeded" to second_view() through HttpResponseRedirect however I got this error message. I am new to python and django so this does not really make a clear sense to me. Your help is so much appreciated. Thanks
By default the django HttpRequest object doesn't have an attribute named flash. That's why you are getting this error. You can see available attributes here: https://docs.djangoproject.com/en/1.9/ref/request-response/#httprequest-objects
But there's no reason why you can't add one.
def first_view(request):
request.flash = {'message'] : 'Operation succeeded!'}
return HttpResponseRedirect(reverse(second_view))
def second_view(request):
try:
print request.flash['message']
request.flash.keep('message')
except:
pass
return HttpResponseRedirect(reverse(third_view))
But from where your flash.keep comes from i have no idea!! As pointed out by wtower it's more usual to rely on the django messages framework for this sort of thing.
I have this String that I need to pass into a REST request
{"notification":{"tag":"MyTag"}}
I'm trying to turn into an object using the JSON module in python.
This is my attempt so far
import json
obj = json.dumps([{'notification': ('{tag : MyTag}')}])
But it isn't parsed correctly so the REST request won't work. Anyone have any ideas?
Just dump your dictionary as is, replace:
obj = json.dumps([{'notification': ('{tag : MyTag}')}])
with:
obj = json.dumps({"notification": {"tag": "MyTag"}})
I have been working with a couple of web APIs but this one has me perplexed. I can't work out what im going wrong.
this code works on one api, but not this one.
response = urllib.request.urlopen(self.query_base)
reader = codecs.getreader("utf-8")
obj = json.load(reader(response))
return obj
this gives me the following errror
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f602' in position 4096: character maps to <undefined>
I have tried:
response = urllib.request.urlopen(self.query_base)
obj = json.load(response.decode("utf-8"))
return obj
which gives:
AttributeError: 'HTTPResponse' object has no attribute 'decode'
and,
response = urllib.request.urlopen(self.query_base).read()
obj = json.load(response)
return obj
which gives
AttributeError: 'bytes' object has no attribute 'read'
and,
response = urllib.request.urlopen(self.query_base)
obj = json.load(response)
which gives
TypeError: the JSON object must be str, not 'bytes'
along with maany other combinations of things I have found in other similar threads on here
I don't remember ever having this problem before, im sure ive missed something but I can't see what.
Your initial attempt is already correct. If it wasn't, you'd get decoding errors.
You have, instead, got encoding errors, moving from Unicode back to bytes. This is invariably caused by you using print() or trying to write the data to a file object. When printing, this is usually caused by your console not being able to handle the output. See python3 print unicode to windows xp console encode cp437 for example.
Your second attempt failed because you didn't read the response, then use json.loads() (since you are passing in a string now):
response = urllib.request.urlopen(self.query_base)
obj = json.loads(response.read().decode("utf-8"))
# ^ ^^^^^^^
return obj
Your 3rd attempt did use .read() but you forgot to decode that time, and again did not use json.loads():
response = urllib.request.urlopen(self.query_base).read()
# you didn't forget this ^^^^^^^
obj = json.loads(response.decode('utf-8'))
# ^ ^^^^^^^^^^^^^^^^
return obj
The last attempt passed in the raw response, without decoding the data.
response = urllib.request.urlopen(self.query_base).read()
obj = json.loads(response)
return obj
This code should work. json.load is looking to read from a file stream. json.loads is what you want when reading JSON from a string.
ok, just incase anyone has this issue and reads this thread later
response = urllib.request.urlopen(self.query_base)
reader = codecs.getreader("utf-8")
obj = json.load(reader(response))
return ascii(obj)
worked fine.
thanks to Martijn Pieters