Since you're using requests, you should use the response's json method.
import requests
response = requests.get(...)
data = response.json()
It autodetects which decoder to use.
Answer from pswaminathan on Stack OverflowSince you're using requests, you should use the response's json method.
import requests
response = requests.get(...)
data = response.json()
It autodetects which decoder to use.
You can use json.loads:
import 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().
Format of a JSON response with Python - Stack Overflow
json - Python API response - How to format/choose layout of reponse - Stack Overflow
Converting Response to JSON?
How to Parse JSON Response in Python? - TestMu AI Community
Videos
The json library in python is very useful especially in working with JSON objects. I would specifically look at the json.dump and json.dumps methods. If you look at the official documentation, json.dumps returns a string and takes a separators parameter and indent parameter.
import json, requests
response = requests.get("http://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=1341&routeid=49&format=json")
print(json.dumps(response.json(), separators=(",",":"), indent=4)
As noted above, the u before a string denotes a unicode string, which you can safely overlook for now.
The 'u' stands for unicode string. The return type is a key-value(dictionary) datatype
import json, requests
import pprint
response = requests.get("http://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=1341&routeid=49&format=json")
data = response.json()
pprint.pprint(data) #Better view
print data['numberofresults'] #Key-Value
Hi all, im trying to grab some data from a website using the requests module in Python. Here is what I have:
import requests, json
apiEndpoint = 'website.com'
r = requests.post(url = apiEndpoint)
data = r.json()
When I do a print(type(r)) I get <class 'requests.models.Response'>
When I do a print(type(data)) I get <class 'list'>
When I want to iterate through the values of data, I am getting an error.
for i in range(len(data['value'])):
for item in data['value'][i]['value_i_want']:do something
The error I am receiving is:
"TypeError: list indices must be integers or slices, not str"
So it converted the response into a list, when I want it to convert into JSON so I can access the data easily. Any ideas?
When I printed response.read() I noticed that b was preprended to the string (e.g. b'{"a":1,..). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string'), I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8'). Once it was in a string type my problem was solved and I was easily able to iterate over the dict.
I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:
from urllib.request import urlopen
import json
# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)
# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)
print(json_obj['source_name']) # prints the string with 'source_name' key
You can also use python's requests library instead.
import requests
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = requests.get(url)
dict = response.json()
Now you can manipulate the "dict" like a python dictionary.
Assuming value is dictionary
to acess the value of name from value dictionary use value['name']
for key, value in repository.items():
print(f"key {key} has value {value['name']}")
from the image you shared, you can get the value of name by using this repository['data'][key]['name']
if there are list of responses
example:
repository=[{key1:{'name':name1}},{key2:{'name':name2}}
for item in repository:
key=next(iter(item))
print(item[key]['name'])
repository is a list holding all responses
Try using json.loads().
For example to get the value of name you could parse your json into a python dict and retrieve it from there.
for key, value in repository.items():
value_dict = json.loads(value)
print(value_dict["name"])
Hi,
I would like to read json into Python code, and then output processed json. In order to get started with this, I have written very basic Python, and am attempting to read in very basic json I found online.
The input json is:
{
"firstName": "John",
"lastName": "Doe",
"hobbies": ["biking", "coding", "rapping"],
"age": 35,
"children": [
{
"firstName": "hector",
"age": 6
},
{
"firstName": "cassandra",
"age": 8
}
]
}The code is:
import json
if __name__ == '__main__':
print( "start" )
# read and load input json
json_input_filename = "input.json"
json_input = open( json_input_filename )
json_input_dict = json.load( json_input )
# write output json
json_output_filename = "output.json"
with open( json_output_filename, 'w' ) as json_output:
json.dump( json_string, json_output )
print( f"end" )and the output is:
"{\"firstName\": \"John\", \"lastName\": \"Doe\", \"hobbies\": [\"biking\", \"coding\", \"rapping\"], \"age\": 35, \"children\": [{\"firstName\": \"hector\", \"age\": 6}, {\"firstName\": \"cassandra\", \"age\": 8}]}"What can I do in order to preserve something resembling the original formatting? I'm going to load this output into some other code in order to process it further.
Thank you very much