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.
SyntaxFollowing is the syntax of using the json.decoder attribute −
import json.decoderFunctions and Classes
The json.decoder attribute provides the following key functions and classes −
In this example, we use the JSONDecoder class to parse a JSON string −
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 −
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 −
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 −
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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4