i have a method that does some calculations and must return a dictionary as shown below in the code section.
the method can not return the dictionary as it contains non serialized data.
i tried to enocod it as explained in the link below
https://pynative.com/online-python-code-editor-to-execute-python-code/
and her as well
TypeError: Object of type 'float32' is not JSON serializable
but i still receive the same error message.
please let me know how to solve this issue
code:
resultsDict = {
"pixelsValuesSatisfyThresholdInWindowSegment":json.dumps(numpyData,cls=NumpyArrayEncoder),
...
...
...
}
return resultsDict
error message
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type float32 is not JSON serializable
I just did the following
resultsDict =
{"pixelsValuesSatisfyThresholdInWindowSegment":str(pixelsValuesSatisfyThresholdInWindowSegment)
}
and it is working.
I was following a tutorial that how to use elasticsearch with python (link=
https://tryolabs.com/blog/2015/02/17/python-elasticsearch-first-steps/#contacto) i faced this error.
import json
r = requests.get('http://localhost:9200')
i = 1
while r.status_code == 200:
r = requests.get('http://swapi.co/api/people/'+ str(i))
es.index(index='sw', doc_type='people', id=i, body=json.loads(r.content))
i=i+1
print(i)
TypeError: the JSON object must be str, not 'bytes'
You are using Python 3, and the blog post is aimed at Python 2 instead. The Python 3 json.loads() function expects decoded unicode text, not the raw response bytestring, which is what response.content returns.
Rather than use json.loads(), leave it to requests to decode the JSON correctly for you, by using the response.json() method:
es.index(index='sw', doc_type='people', id=i, body=r.json())
import requests
import json
s = requests.Session()
s.params["key"] = "MY_KEY"
s.params["cx"] = "MY_CX"
s.params["num"] = 1
result = s.get('https://www.googleapis.com/customsearch/v1', params={"q": "Search query"})
Everything is working fine and I do get a result back but it's JSON. What I want is one thing. Since my result only gives 1 search result, I want the link of that search result. From I've understood that link value is under the keys "item" and then "link". I've tried lots of things but I keep getting either one of these errors below.
TypeError: 'Response' object is not subscriptable
NameError: name 'json' is not defined
AttributeError: 'Response' object has no attribute 'read'
TypeError: the JSON object must be str, not 'Response'
What am i doing wrong and what's the solution?
Usually my webservice built with Bottle return JSON files, which works fine. But, I've an exception that need to call a local function.
Here is what I tried to do:
import json
def getData():
return json.dumps({'data': someData })
def function():
try:
# Fail
except:
print getData()
print type(getData())
json.load(getData())
So it prints:
{"data": "myData"}
<type 'str'>
[...]
AttributeError: 'str' object has no attribute 'read'
So json.dumps gives me a string. How can I use it as JSON ?
json.load loads JSON from a file object.
json.loads loads from a string. This is what you want.
Use json.loads instead of json.load. As per the docs.
This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 29 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"]')