Python json.decoder Attribute



The Python json.decoder attribute is a module-level component that provides functionalities for decoding JSON-encoded strings into Python objects.

This attribute is primarily used to parse JSON data received from APIs, files, or other sources and convert them into native Python data structures.

Syntax

Following is the syntax of using the json.decoder attribute −

import json.decoder

Functions and Classes

The json.decoder attribute provides the following key functions and classes −

  • JSONDecoder: A class for decoding JSON data into Python objects.
  • scanstring: A function for scanning and parsing JSON string values.
  • make_scanner: A function that creates a scanner for tokenizing JSON data.
  • JSONArray: Internal function to parse JSON arrays.
  • JSONObject: Internal function to parse JSON objects.

Example: Using JSONDecoder

In this example, we use the JSONDecoder class to parse a JSON string −

Open Compiler
import json # Define JSON string json_string = '{"name": "John", "age": 30, "city": "New York"}' # Create JSONDecoder instance decoder = json.decoder.JSONDecoder() # Decode JSON string into a Python dictionary parsed_data = decoder.decode(json_string) print("Decoded JSON:", parsed_data)

Following is the output obtained −

Decoded JSON: {'name': 'John', 'age': 30, 'city': 'New York'}

Example: Using scanstring() Function

The scanstring() function is used for scanning and extracting JSON string values −

Open Compiler
import json.decoder # Define a JSON string json_text = '"Hello, World!"' # Parse string using scanstring parsed_string, end_pos = json.decoder.scanstring(json_text, 1) print("Parsed String:", parsed_string)

Following is the output of the above code −

Parsed String: Hello, World!

Example: Handling Invalid JSON

Invalid JSON data will raise a ValueError as shown in the example below −

Open Compiler
import json # Define invalid JSON string invalid_json = '{"name": "John", "age": 30,}' # Create JSONDecoder instance decoder = json.decoder.JSONDecoder() try: # Attempt to decode invalid JSON parsed_data = decoder.decode(invalid_json) print("Parsed Data:", parsed_data) except ValueError as e: print("Error:", e)

We get the output as shown below −

Error: Expecting property name enclosed in double quotes: line 1 column 28 (char 27)

Example: Parsing JSON Arrays

The JSONArray function is used internally to parse JSON arrays −

Open Compiler
import json.decoder # Define JSON array string json_array_string = '[1, 2, 3, 4, 5]' # Create JSONDecoder instance decoder = json.decoder.JSONDecoder() # Decode JSON array parsed_array = decoder.decode(json_array_string) print("Parsed Array:", parsed_array)

The result produced is as follows −

Parsed Array: [1, 2, 3, 4, 5]
python_json.htm
Advertisements