Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python json.decoder.JSONDecoder.object_pairs_hook Attribute



The Pythonjson.decoder.JSONDecoder.object_pairs_hook attribute is an optional parameter used to define a custom function that processes JSON objects as lists of key-value pairs instead of dictionaries.

It allows preserving order in JSON objects, handling duplicate keys, or transforming data into custom structures likeOrderedDict.

Syntax

Following is the syntax of using theobject_pairs_hook attribute −

json.decoder.JSONDecoder(object_pairs_hook=function)

Parameter

It is a function that processes JSON key-value pairs as a list of tuples.

Return Value

Theobject_pairs_hook function modifies how JSON objects are parsed, returning a custom object (e.g., anOrderedDict instead of a standard dictionary).

Example: Preserving Key Order with OrderedDict

The default JSON decoder does not guarantee key order. Using theobject_pairs_hook attribute withOrderedDict preserves the order −

import jsonfrom collections import OrderedDict# JSON string with unordered keysjson_string = '{"b": 2, "a": 1, "c": 3}'# Create JSONDecoder instance with OrderedDictdecoder = json.decoder.JSONDecoder(object_pairs_hook=OrderedDict)# Decode JSONparsed_data = decoder.decode(json_string)print("Ordered JSON:", parsed_data)

Following is the output obtained −

Ordered JSON: OrderedDict([('b', 2), ('a', 1), ('c', 3)])

Example: Converting JSON to a List of Tuples

Theobject_pairs_hook attribute can store JSON data as a list of tuples instead of a dictionary −

import json# Custom function to return key-value pairs as a list of tuplesdef as_list(pairs):   return list(pairs)# JSON string with key-value pairsjson_string = '{"x": 10, "y": 20, "z": 30}'# Create JSONDecoder instance with as_list functiondecoder = json.decoder.JSONDecoder(object_pairs_hook=as_list)# Decode JSONparsed_data = decoder.decode(json_string)print("JSON as List of Tuples:", parsed_data)

Following is the output of the above code −

JSON as List of Tuples: [('x', 10), ('y', 20), ('z', 30)]

Example: Handling Duplicate Keys in JSON

By default, JSON parsing ignores duplicate keys. Withobject_pairs_hook attribute, we can detect duplicates −

import json# Custom function to detect duplicate keysdef detect_duplicates(pairs):   seen_keys = set()   for key, value in pairs:      if key in seen_keys:         raise ValueError(f"Duplicate key detected: {key}")      seen_keys.add(key)   return dict(pairs)# JSON string with duplicate keysjson_string = '{"name": "Alice", "age": 25, "name": "Bob"}'# Create JSONDecoder instance with detect_duplicates functiondecoder = json.decoder.JSONDecoder(object_pairs_hook=detect_duplicates)try:   # Decode JSON   parsed_data = decoder.decode(json_string)   print("Parsed JSON:", parsed_data)except ValueError as e:   print("Error:", e)

We get the output as shown below −

Error: Duplicate key detected: name

Example: Converting JSON to a Custom Data Structure

You can use theobject_pairs_hook attribute to transform JSON into a custom class −

import json# Custom class to store JSON dataclass CustomObject:   def __init__(self, pairs):      self.data = dict(pairs)   def __repr__(self):      return f"CustomObject({self.data})"# JSON stringjson_string = '{"username": "john_doe", "score": 100}'# Create JSONDecoder instance with CustomObjectdecoder = json.decoder.JSONDecoder(object_pairs_hook=CustomObject)# Decode JSONparsed_data = decoder.decode(json_string)print("Custom Object:", parsed_data)

The result produced is as shown below −

Custom Object: CustomObject({'username': 'john_doe', 'score': 100})
python_json.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp