Unable to turn JSON to Dictionary in python from get request - python

I am trying to turn json I got from a GET request using an API into a dictionary that I can use. Here is what I did:
response = requests.get(API)
response_dict = json.loads(response.json())
print(response_dict)
I get the error:
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not dict

Carefully read the error. It suggests that response.json() already returns a dict. There is no need to call json.loads (which accepts a string) on it.
response = requests.get(API)
response_dict = response.json()
is all you need.

Related

Parsing a JSON string and store in a variable

Hi Guys I am calling this API to see the live data of a price from Coingecko, I am trying to parse the json file but keep getting a error in my code when i use json.loads. I imported json and still get this error
Here is a snippet of my code
import json
import requests
class LivePrice(object): #Coingecko API
def GetPrice(self, coin):
coinprice = coin
Gecko_endpoint = 'https://api.coingecko.com/api/v3/simple/price?ids='
currency = '&vs_currencies=usd'
url = Gecko_endpoint + coinprice + currency
r = requests.get(url, headers = {'accept': 'application/json'})
y = json.loads(r)
#print(r.json()[coinprice]['usd'])
if I use this print function i get the price but I want to be able to use the variable and pass it to another class to do some calculation
Just trying to make a simple trading bot for fun while using Alpaca API for paper trading
Traceback (most recent call last):
File "AlapacaBot.py", line 76, in <module>
r.GetPrice(Bitcoin)
File "AlapacaBot.py", line 65, in GetPrice
y = json.loads(r)
File "/usr/lib/python3.8/json/__init__.py", line 341, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not Response
I am following the example from w3schools but I keep getting an error
https://www.w3schools.com/python/python_json.asp
json.loads only accepts the types listed in your error.
requests get method returns a Response object, not one of those types. The W3Schools link is not a replacement for the Python Requests module documentation, as it only shows strings, not Response objects.
Response objects have a json() function to get the body as a dictionary, which you commented out
r = requests.get(url, headers = {'accept': 'application/json'})
y = r.json()
print(y[coin]['usd'])
Your code is almost correct. You only need to use the requests.json() to retrieve the json information
import json
import requests
class LivePrice: #Coingecko API
def GetPrice(coin):
coinprice = coin
Gecko_endpoint = 'https://api.coingecko.com/api/v3/simple/price?ids='
currency = '&vs_currencies=usd'
url = Gecko_endpoint + coinprice + currency
r = requests.get(url, headers = {'accept': 'application/json'})
y = r.json()
print(y[coinprice]['usd'])
LivePrice.GetPrice("bitcoin")

How to get value from JSON format

I am using Python request module to get API response. The response is should be JSON format. From the response how do I retrieve the specific value?
Example of API response:
{
id: 2337975,
sha: "eac6910f89883110e673db27456b67f542df6d75",
ref: "mail-gun",
status: "manual",
created_at: "2021-03-01T09:15:02.409Z",
updated_at: "2021-03-01T09:19:14.983Z",
web_url: "https://gitlab.com/optimus/optimus-ci/-/pipelines/2337975"
}
From here I want retrieve on ID :2337975 assign into a variable in Python.
Here is my code
url = f'https://gitlab.com/api/v4/projects/{pid}/pipelines?updated_after={update_after}&ref={branch}&status=manual'
headers = {'Authorization' : 'Bearer xxxxxxxx'}
response = requests.get(url, headers=headers)
output = json.loads(response.text)
print(output)
I can print the whole JSON format by print(output), but I only want to get a Id value.
Anybody can help?
change this:
output = json.loads(response.text)
to this: (using json function you can receive the json response in string format)
load the response into a python dictionary
response_json = json.loads(response.json())
and access the id key from response dictionary
variable = response_json["id"]
You should save this JSON code in a .json file, then you can open it, load it and then use variable ["id"].
parse the json and use the id as key in json to extract.
loaded_json = json.loads(json_data)
for x in loaded_json:
print("%s: %d" % (x, loaded_json[id]))
since the returned value of a json is an object (JavaScript Object Notation) you can treat it as such and just destructure the object with the [] notation as other pointed out response_json["id"]
I solve this using a naive way. which is convert the object to JSON > python list > python dictionary
response = requests.get(url, headers=headers, proxies=proxyDict)
response_list = response.json()
response_dict = response_list[0]
print(response_dict["id"])

Unable to use json.loads() due to 'expected string or buffer'

I've been stuck trying to pull a certain bit from this api response for a while.
my code:
payload = {
'symbol':'RPX-ETH',
'from':'100603756',
'to':'9516619507'
}
request = requests.get('https://api.kucoin.com/v1/open/chart/history',
params=payload)
jdata = json.loads(request)
print jdata['c']
However I keep getting this error:
TypeError: expected string or buffer
The api response only using .json() for reference:
{u'c': [0.00024, 0.000171, 0.000163, 0.000151, 0.000159, 0.000164}
request is the whole requests response object. You need to pass request.body.
However there is no need to do that at all because request.json() does it for you and returns a parsed Python data structure.
You can use the request.json to access the return data as a dictionary.
Replace
jdata = json.loads(request)
print jdata['c']
With
jdata = request.json()
print jdata['c']

Get Specific Data form request.post response in Python

I am using sendgrid api to send email to users and then check the status,
res = requests.post(url)
print type(res)
and it prints type as <class 'requests.models.Response'>
on the Postman API client I am getting this:
{
"message": "error",
"errors": [
"JSON in x-smtpapi could not be parsed"
]
}
I want to fetch only the message value from response. I have written the following piece of code but doesn't work:
for keys in res.json():
print str(res[keys]['message'])
You don't need to loop; just access the 'message' key on the dictionary returned by the response.json() method:
print res.json()['message']
It may be easier to follow what is going on by storing the result of the response.json() call in a separate variable:
json_result = res.json()
print json_result['message']
The reason Postman API returns an error message is because your POST didn't actually contain any data; you probably want to send some JSON to the API:
data = some_python_structure
res = requests.post(url, json=data)
When you use the json argument, the requests library will encode it to JSON for you, and set the correct content type header.

python, Json and string indices must be integers, not str

I am using Python, and I sent a request to a URL and received a reply using httplib2. The reply I got was in JSon, how do I access a specific parameter. What I have at the moment is:
resp, content = parser.request(access_token_uri, method = 'POST', body = params, headers = headers)
raise Exception(content['access_token'])
and I get the error
string indices must be integers, not str
How do I do it?
Thanks
Well if the response type is json and it comes in type str.
If you are running 2.4 of Python use simplejson if 2.6 use json:
import json
# Your code
retdict = json.loads(content)
Then treat it like a dictionary.
accesstoken = retdict['access_token']
You can use dump;
result = json.dumps(content)
result = json.loads(result)

Categories

Resources