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

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)

Related

Unable to turn JSON to Dictionary in python from get request

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.

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

Response from API is in a dictionary format

I'm having an issue getting a response from an rest API into a json format with Pandas. Here's my code:
import pandas as pd
import numpy as np
import requests
import json
headers = {
'Authorization': 'Token token="mytoken"',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache--url',
}
response = requests.get('https://www.someurl.com/api/path', headers=headers)
data = response.json()
This is my issue: Whenever I check the data type that I get in response, it is in a dictionary format, like so:
In[2]: type(data)
Out[2]: dict
Because it returns text that's in a JSON format, but it comes into my code as a dictionary, I cannot use panda's .read_json() command because it appears that it's expecting a JSON datatype. Whenever I try to do that, it returns this:
In[3]: pd.read_json(data)
Out[3]: ValueError: Invalid file path or buffer object type: <class 'dict'>
I think the main issue is that my response returns in the form of a dictionary instead of pure JSON, and not because of the syntax within the JSON data itself, but by no means am I an expert in this subject. Let me know what you guys think.
Here's the documentation to the API I'm using:
https://documentation.joinhandshake.com/v1.0/reference#introduction
Any help would be greatly appreciated.
Your request does not return a Python dictionary -- the requests module's .json() method returns a dictionary. If your response is in json and you just want to use the string to load it in to pandas, use response.text.

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 attribute data from Json

I'm implemented a code to return Json value like this
{ "key1":"1", "key2":"2", ......}
But I want to get only value of key1. so I first defined info to get Json.
info = requests.get(url, headers=headers)
And use info.text['key1'] to get value of key1. but i got error. could anyone suggest any solution?
JSON is a format, but the data are included as text. Inside the info.text you have a string.
If you want to access the json data you can do info.json()['key1']. This will work only if the response content type is defined as JSON, to check that do
info.headers['content-type'] should be application/json; charset=utf8
http://docs.python-requests.org/en/master/
Otherwise you will have to manually load the text to json, with json library for example
import json
response = requests.get(url, headers=headers)
data = json.loads(response.text)
import json
info = requests.get(url, headers=headers)
jsonObject = json.loads(info)
key1= jsonObject['key1']
or
jsonObject = info.json()
key1= jsonObject['key1']

Categories

Resources