Parse a JSON response using Python requests library (2024)

Updated on: | 4 Comments

In this article, we will learn how to parse a JSON response using the requests library. For example, we are using a requests library to send a RESTful GET call to a server, and in return, we are getting a response in the JSON format, let’s see how to parse this JSON data in Python.

We will parse JSON response into Python Dictionary so you can access JSON data using key-value pairs. Also, you can prettyPrint JSON in the readable format.

The response of the GET request contains information we called it as a payload. We can find this information in the message body. Use attributes and methods of Response to view payload in the different formats.

We can access payload data using the following three methods of a requests module.

  • response.content used to access payload data in raw bytes format.
  • response.text: used to access payload data in String format.
  • response.json() used to access payload data in the JSON serialized format.

The JSON Response Content

The requests module provides a builtin JSON decoder, we can use it when we are dealing with JSON data. Just execute response.json(), and that’s it. response.json() returns a JSON response in Python dictionary format so we can access JSON using key-value pairs.

You can get a 204 error In case the JSON decoding fails. The response.json()raises an exception in the following scenario.

  • The response doesn’t contain any data.
  • The response contains invalid JSON

You must check response.raise_for_status() or response.status_code before parsing JSON because the successful call to response.json() does not indicate the success of the request.

In the case of HTTP 500 error, some servers may return a JSON object in a failed response (e.g., error details with HTTP 500). So you should execute response.json() after checking response.raise_for_status() or check response.status_code.

Let’s see the example of how to use response.json() and parse JSON content.

In this example, I am using httpbin.org to execute a GET call. httpbin.orgis a web service that allows test requests and responds with data about the request. You can use this service to test your code.

import requestsfrom requests.exceptions import HTTPErrortry: response = requests.get('https://httpbin.org/get') response.raise_for_status() # access JSOn content jsonResponse = response.json() print("Entire JSON response") print(jsonResponse)except HTTPError as http_err: print(f'HTTP error occurred: {http_err}')except Exception as err: print(f'Other error occurred: {err}')Code language: Python (python)

Output:

Entire JSON response{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}, 'origin': '49.35.214.177, 49.35.214.177', 'url': 'https://httpbin.org/get'}

Iterate JSON Response

Let’s see how to iterate all JSON key-value pairs one-by-one.

print("Print each key-value pair from JSON response") for key, value in jsonResponse.items(): print(key, ":", value)Code language: Python (python)

Output:

Print each key-value pair from JSON responseargs : {}headers : {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.21.0'}origin : 49.35.214.177, 49.35.214.177url : https://httpbin.org/get

Access JSON key directly from the response using the key name

print("Access directly using a JSON key name")print("URL is ")print(jsonResponse["url"])Code language: Python (python)

Output

URL is https://httpbin.org/get

Access Nested JSON key directly from response

print("Access nested JSON keys")print("Host is is ")print(jsonResponse["headers"]["Host"])Code language: Python (python)

Output:

Access nested JSON keysURL is httpbin.org
Parse a JSON response using Python requests library (2024)

FAQs

How to parse JSON in Python requests? ›

loads() is used to parse JSON data from a string and convert it into a Python data structure. For example, the string '{"name": "John", "age": 30, "city": "New York"}' would be converted to {'name': 'John', 'age': 30, 'city': 'New York'} when using json. loads() .

How do you parse JSON response data in Python? ›

To read JSON data, you can use the built-in json module (JSON Encoder and Decoder) in Python. The json module provides two methods, loads and load, that allow you to parse JSON strings and JSON files, respectively, to convert JSON into Python objects such as lists and dictionaries.

How to get response in JSON format in python requests? ›

Getting JSON with Python Requests Library. To request JSON data from the server using the Python Requests library, call the request. get() method and pass the target URL as a first parameter. The Python Requests Library has a built-in JSON decoder and automatically converts JSON strings into a Python dictionary.

How to parse JSON on Python? ›

If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.

How to parse a JSON response? ›

Example - Parsing JSON

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How to extract value from JSON response in Python? ›

Open the JSON file in read-only mode using the Python with() function. Load the JSON data into a variable using the Python load() function. Now, get the value of keys in a variable. Now convert the value of the dictionary into a list and slice the string using the split function.

How to get JSON response from rest API in Python? ›

After making the get request to an API we store the JSON data in a variable “API_Data” using the response. json() method. Then we iterate over the JSON data using for loop and print the data by using the keys.

How to format JSON response in Python? ›

To write a Python object as JSON Pretty Print format data into a file, json. dump() method is used. Like json. dumps() method, it has the indents and separator parameters to write beautified JSON.

How to parse JSON from an API using Python? ›

To parse JSON strings in Python, use the json. loads() method from the built-in json module. This method converts a JSON string into a Python object. If the input string is not valid JSON, json.

How to send a JSON response in Python? ›

Here's an example of how to handle the response: import requests url = 'https://www.example.com/api' data = {'username': 'my_username', 'password': 'my_password'} headers = {'Content-type': 'application/json'} response = requests. post(url, json=data, headers=headers) if response.

How to get the response in JSON format? ›

Response: json() method

The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

How do I access JSON responses? ›

Getting a specific property from a JSON response object

Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.

How to parse data in Python? ›

In Python programming, data parsing is done using built-in libraries such as json, xml. etree. ElementTree, and csv. These libraries provide functions and methods that allow you to parse data from different sources and convert them into usable formats.

How to parse JSON to table in Python? ›

You add a new load_traffic_data_as_table() function that returns the JSON data in a Table format.
  1. The load_json_from_file() function provided by the RPA. JSON library returns the file contents (string) in JSON format.
  2. The create_table() function from the RPA. Tables library converts the JSON format into a Table.

How to parse JSON key-value in Python? ›

Python Parse JSON String

To parse JSON string Python firstly we import the JSON module. We have a JSON string stored in a variable 'employee' and we convert this JSON string to a Python object using json. loads() method of JSON module in Python. After that, we print the name of an employee using the key 'name' .

How to convert request to JSON in Python? ›

You can use the json. dumps() function provided by the JSON module to create JSON from a Python dictionary. This function takes a Python object, typically a dictionary, and converts it into a JSON string representation.

How to pass JSON request in Python? ›

To post a JSON to the server using Python Requests Library, call the requests. post() method and pass the target URL as the first parameter and the JSON data with the json= parameter. The json= parameter takes a dictionary and automatically converts it to a JSON string.

How to parse a list of JSON in Python? ›

Python Parse multiple JSON objects from file
  1. Create an empty list called jsonList.
  2. Read the file line by line because each line contains valid JSON. i.e., read one JSON object at a time.
  3. Convert each JSON object into Python dict using a json. loads()
  4. Save this dictionary into a list called result jsonList.

Top Articles
7 ways to do it faster
10 Steps to Financial Security Before Age 30
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 5949

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.