Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python json.JSONDecoder.decode() Method



The Pythonjson.JSONDecoder.decode() method is used to decode a JSON-encoded string into a corresponding Python object.

This method is useful when manually parsing JSON data, especially when working with custom deserialization logic.

Syntax

Following is the syntax of the Pythonjson.JSONDecoder.decode() method −

json.JSONDecoder().decode(s)

Parameters

This method accepts a JSON-encoded string as a parameter that needs to be decoded.

Return Value

This method returns a Python object that represents the parsed JSON data.

Example: Basic Usage of decode()

In this example, we use thejson.JSONDecoder.decode() method to manually decode a JSON string −

import json# JSON stringjson_string = '{"name": "Alice", "age": 25, "city": "New York"}'# Create JSONDecoder instancedecoder = json.JSONDecoder()# Decode JSON stringdata = decoder.decode(json_string)print("Decoded Data:", data)

Following is the output obtained −

Decoded Data: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Example: Using decode() with JSON Arrays

Thedecode() method can also handle JSON arrays and convert them into Python lists −

import json# JSON string (array)json_string = '[{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]'# Create JSONDecoder instancedecoder = json.JSONDecoder()# Decode JSON stringdata = decoder.decode(json_string)print("Decoded List:", data)

We get the output as shown below −

Decoded List: [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

Example: Handling Special Constants

Thedecode() method can also handle special JSON constants such as NaN and Infinity when using theparse_constant parameter −

import json# Custom function to handle special constantsdef parse_constant_custom(value):   return f"Special value: {value}"# JSON string with special constantsjson_string = '{"value1": NaN, "value2": Infinity, "value3": -Infinity}'# Create JSONDecoder instance with parse_constantdecoder = json.JSONDecoder(parse_constant=parse_constant_custom)# Decode JSON stringdata = decoder.decode(json_string)print("Parsed Data:", data)

After executing the above code, we get the following output −

Parsed Data: {'value1': 'Special value: NaN', 'value2': 'Special value: Infinity', 'value3': 'Special value: -Infinity'}

Example: Custom Object Conversion

Theobject_hook parameter allows us to convert JSON objects into custom Python objects while decoding −

import json# Sample classclass Person:   def __init__(self, name, age):      self.name = name      self.age = age# Custom function to decode JSON into Person objectsdef custom_decoder(obj):   return Person(obj["name"], obj["age"])# JSON stringjson_string = '{"name": "Bob", "age": 30}'# Create JSONDecoder instance with object_hookdecoder = json.JSONDecoder(object_hook=custom_decoder)# Decode JSON stringperson = decoder.decode(json_string)print("Decoded Person:", vars(person))

Following is the output of the above code −

Decoded Person: {'name': 'Bob', 'age': 30}

Example: Preserving Key Order

By default, Python dictionaries maintain order in Python 3.7+, but we can explicitly use theobject_pairs_hook parameter to load a JSON object while preserving key order −

import jsonfrom collections import OrderedDict# JSON stringjson_string = '{"c": 3, "b": 2, "a": 1}'# Create JSONDecoder instance with object_pairs_hookdecoder = json.JSONDecoder(object_pairs_hook=OrderedDict)# Decode JSON stringdata = decoder.decode(json_string)print("Ordered Data:", data)

The result produced is as follows −

Ordered Data: OrderedDict({'c': 3, 'b': 2, 'a': 1})
python_json.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp