Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to parse a JSON response from the requests library?

I'm using the python requests module to send a RESTful GET to a server, for which I get a response in JSON. The JSON response is basically just a list of lists.

What's the best way to coerce the response to a native Python object so I can either iterate or print it out using pprint?

like image 865
felix001 Avatar asked Jun 01 '13 21:06

felix001


People also ask

How get JSON data from GET request in Python?

To request JSON from a URL using Python, you need to send an HTTP GET request to the server and provide the Accept: application/json request header with your request. The Accept header tells the server that our Python client is expecting JSON.

What does Response JSON () do Python?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.


2 Answers

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.

like image 141
pswaminathan Avatar answered Oct 07 '22 17:10

pswaminathan


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().

like image 32
Simeon Visser Avatar answered Oct 07 '22 19:10

Simeon Visser