Get a JSON object in python - python

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.

Related

"dict" being interpreted as a "list" and I can't tell why

I have a strange problem and I can't seem to find a solution. I'm creating a Python app that sends a get request to an endpoint, fetches some data in JSON format and processes it to insert it into a database later. I have to classes, one is like APIClient, and the other is just a namespace to hold some methods to transform the data, let's call it APITransform.
There is a problematic method in APITransform, so here's the code.
#api.py module"
class APITransform:
...
#staticmethod
def flatten(data:dict, method:str):
if method == "some flattening method from a config file":
return list(data.values())
....
class APIClient:
....
def get_data():
....
response = requests.get(URL, headers, params)
json_resp = response.json()
json_resp = APITransform.flatten(
json_resp, "some flattening method from a config file")
#main.py module
from api import APIClient
api_client = APIClient()
api_client.get_data()
The error traces to APITransform.flatten() with the message:
return list(data.values())
AttributeError: 'list' object has no attribute 'values'
EDIT: The strange thing is that If I print the type of json_resp object before passing it to APITransform.flatten() in get_data(), I get two outputs in two lines: <class dict> and <class list>. It's like get_data() is being called twice, but I searched it in the entire project, I can only find it in two places, the definition in APIClient and call in main.py. I'm out of debugging ideas.
Anyone with an idea? Thanks
the code can raise such an error if the result of the json which is returned from a server, is a list, for example, if the response (from the server) is something like "[1,2,3]" or any other json list, the json_resp variable would be a list, that of course has no values() function. make sure the server returns the data in proper format or use an if statement to check before passing to the flatten function.

How to convert a dict object in requests.models.Response object in Python?

I am trying to test a function which contain an API call. So in the function I have this line of code :
api_request = dict(requests.get(url_of_the_API).json())
So I tried to use patch like this :
#patch('requests.get')
def test_products_list_creator(self, mock_get):
mock_get.return_value = json.dumps({"products":
{
"name": "apple",
"categories": "fruit,red"
}
})
But at the line of my API call, python throw me this error :
AttributeError: 'str' object has no attribute 'json'
I tried to print type(requests.get(url_of_the_API}.json")) to know what it was and I got this : <class 'requests.models.Response'>
There is a lot of questions about convert a Response in dict but didn't found any about converting a dict to a Response.
So how to make my patch callable by the method json() ?
Firstly we need to figure what is required by requests.models.Response's method .json in order to work, this can be done by scrying source code available at github - requests.models source. After reading requests.models.Response.json body we might conclude that if encoding is set, it does simply loads .text. text method has #property decorator, meaning it is computed when accessing .text, this in turn depend on .content which also is computed. After scrying .content it should be clear that if we set ._content value then it will be returned by .content, therefore to make fake Response which do support .json we need to create one and set .encoding and ._content of it, consider following example:
from requests.models import Response
resp = Response()
resp.encoding = 'ascii'
resp._content = b'{"x":100}'
print(resp.json())
output
{'x': 100}
Note that _content value needs to be bytes so if you have dict d then to get value to be put there do json.dumps(d).encode('ascii')

return existing JSON file in flask

i have a method (matching) that returns a JSON file. I want to return this file via a flask method.
when i do this:
#app.route('/search', methods=['POST'])
def json_example():
req_data = request.get_json()
request_text = req_data['request'] #json text that is needed as argument for calling the matching method
json_result = matching(request_text)
return json_result
i get this error:
<title>TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple,
Response instance, or WSGI callable, but it was a TextIOWrapper. // Werkzeug Debugger</title>
playing around with str(json_result), i just get this:
<_io.TextIOWrapper name='result.json' mode='w' encoding='UTF-8'>
Also, jsonify(json_reslult) does not work, since i have a json file and am not trying to convert a string into a json. when trying it gives:
<title>TypeError: Object of type TextIOWrapper is not JSON serializable // Werkzeug Debugger</title>
Any helpis greatly appreciated
Decode request_text first
json_result = matching(json.loads(request_text))

AttributeError: 'bytes' object has no attribute '__dict__'

I totally new in Python and stuck with this error:
I am trying to encode an image and then convert it to json to upload into a no-sql db. But when I am trying to convert it to json I am getting this error:
"AttributeError: 'bytes' object has no attribute 'dict'"
Below is my python code:
import base64
import json
def jsonDefault(object):
return object.__dict__
with open("img123.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print(str)
json_str = {'file_name':'img123','img_str':str}
pytojson = json.dumps(json_str, default=jsonDefault)
print(pytojson)
That happens because you are trying to access a property that a bytes object doesn't have (__dict__). I understand that you need to return a format that can be serialized to JSON.
This works for me, but I don't know if it's the decoding you desire:
def jsonDefault(o):
return o.decode('utf-8')
See TypeError: b'1' is not JSON serializable as well.

Why do I get "'str' object has no attribute 'read'" when trying to use `json.load` on a string? [duplicate]

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"]')

Categories