Load it via json.load():
import json
response = urllib.request.urlopen(req)
result = json.loads(response.readall().decode('utf-8'))
message_id = result['messages'][0]['message-id']
Answer from alecxe on Stack OverflowHi,
I was under the impression that the using .json() to a request made with Python requests, would yield a dictionary object, but it seems I am getting back a string object.
Am I missing a step?
Here is the code:
def otc_holdings():
SIZE = 1
url = 'https://www.otcmarkets.com/research/stock-screener/api'
params = {'securityType' : 'Common Stock,ADRs',
'page':1, 'pageSize': SIZE}
from requests.models import PreparedRequest
req = PreparedRequest()
req.prepare_url(url, params)
print(req.url)
response =requests.get(url,headers = \
USER_AGENTS.random_header(),
params= params).json()
print(response)
print(type(response))
print(response['pages'])
assert response['pages'] == '1'python - How to convert request.data to dict? - Stack Overflow
python - How to parse a JSON response from the requests library - Stack Overflow
python - Convert response.request.body to dict - Stack Overflow
Converting Requests response to JSON or dictionary, please help!
Edit: For post request:
import requests
import json
url = "https://jsonplaceholder.typicode.com/posts/"
payload = {
"userId": 10,
"id": 901,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
headers = {
'content-type': "application/json",
'cache-control': "no-cache",
'postman-token': "c71c65a6-07f4-a2a4-a6f8-dca3fd706a7a"
}
response = requests.request("POST", url, data=json.dumps(payload), headers=headers)
print(type(response.json()))
class 'dict'
You can use something like this:
import requests
url = "https://api.icndb.com/jokes/random"
headers = {
'cache-control': "no-cache",
'postman-token': "77047c8b-caed-2b2c-ab33-dbddf52a7a9f"
}
response = requests.request("GET", url, headers=headers)
print(type(response.json()))
class 'dict'
import json
response_data = json.loads(response.text)
result = response_data.get('result')
you need to deserialize response.text to have it as dict and then user .get with respective key. result is a key in above example. and response was the response of a url call.
Since you're using requests, you should use the response's json method.
Copyimport requests
response = requests.get(...)
data = response.json()
It autodetects which decoder to use.
You can use json.loads:
Copyimport json
import requests
response = requests.get(...)
json_data = json.loads(response.text)
This converts a given string into a dictionary which allows you to access your JSON data easily within your code.
Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().
The cited thread URL query parameters to dict python (
Martijn Pieters's answer) indeed shows how-to convert the query string to a dict. However, one needs to pass the body instead of the splitted query, then it works:
Copydict(urllib.parse.parse_qsl(response.request.body))
So, now I can answer the question myself.
You can use this to Convert Query string to dict
Copystring_query = 'x=100&y=200'
dict_query = {item.split('=')[0]:int(item.split('=')[1]) for item in string_query.split("&")}
print(dict_query)
You can use this Simple Function:
Copydef query_to_dict (query : str) -> dict:
return {item.split('=')[0]:int(item.split('=')[1]) for item in query.split("&")}
body_response = 'x=100&y=200'
dict_query = query_to_dict(body_response)
print(dict_query)
find more information on : python: how to convert a query string to json string?
I have a program that is taking data from two APIs (both from rapidapi) and I was able to get the first one's response to convert to json so that I could take just the value for one key with no problems. But the second response will absolutely not do so. Here is an example of how the response.text is formatted:
{"imdbID":"tt2375844","tmdbID":"334742","imdbRating":24,"imdbVoteCount":285,"tmdbRating":33,"backdropPath":"/jL0osb1ddQ25mjbTTVYhXuNtMfw.jpg","backd
ropURLs":{"1280":"https://image.tmdb.org/t/p/w1280/jL0osb1ddQ25mjbTTVYhXuNtMfw.jpg","300":"https://image.tmdb.org/t/p/w300/jL0osb1ddQ25mjbTTVYhXuNtM
fw.jpg","780":"https://image.tmdb.org/t/p/w780/jL0osb1ddQ25mjbTTVYhXuNtMfw.jpg","original":"https://image.tmdb.org/t/p/original/jL0osb1ddQ25mjbTTVYh
XuNtMfw.jpg"},"originalTitle":"Fractured","genres":[18,27,53],"countries":[],"year":2015,"runtime":89,"cast":["Eric Roberts","Jake Busey","Shena Adl
","Athena Isabel Lebessis"],"significants":["Lance Kawas"],"title":"Fractured","overview":"May Oster, played by Athena Lebessis, is a beautiful,And so on. Here is the code that I'm trying to finish:
for id in imdb_ids:
querystring = {"country":"us","imdb_id":id}
streamresponse = requests.request("GET", url, headers=headers, params=querystring)Up to this point, it works fine. But converting it is impossible. I've tried streamresponse.json(), json.loads(streamresponse), ast.literal_eval(streamresponse), and a few other things. Every time I try to convert to json I get a bunch of errors with the main one being json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). I think this means that the response.text is not formatted like json, but, from what I can tell, it is.
I just want to take just certain information from the response.text (like "title") so if anyone can give me some pointers, I would really appreciate it.
This looks like a JSON string. You can parse it with json.loads()
>>> import json
>>> json.loads(response.text)
Assuming the response you are referring comes from using the requests library, you can also simply do response.json()
This is simple:
import json
resp_text = request.text
dict=json.loads(res_text)
this will convert your response text in to dictionary