Menu
Coddy logo textTech

Custom JSON Decoding

Lesson 9 of 9 in Coddy's Python JSON course.

Custom JSON decoding is an advanced feature of Python's json module that allows you to control how JSON data is converted into Python objects. This is particularly useful when dealing with complex data structures or when you want to create specific Python objects from JSON data.

The JSONDecoder Class

To implement custom JSON decoding, you need to subclass the json.JSONDecoder class and override its object_hook method:


import json

class CustomDecoder(json.JSONDecoder):
    def object_hook(self, dct):
        # Custom decoding logic here
        return dct

Using the Custom Decoder

Once you've defined your custom decoder, you can use it with json.loads() or json.load():


decoded_object = json.loads(json_string, cls=CustomDecoder)

Example: Decoding to Custom Objects

Let's look at a practical example where we decode JSON data into custom Python objects:


import json
from datetime import datetime

class Person:
    def __init__(self, name, birthdate):
        self.name = name
        self.birthdate = birthdate

class CustomDecoder(json.JSONDecoder):
    def object_hook(self, dct):
        if 'name' in dct and 'birthdate' in dct:
            return Person(dct['name'], datetime.fromisoformat(dct['birthdate']))
        return dct

json_string = '{"name": "Alice", "birthdate": "1990-05-15"}'
person = json.loads(json_string, cls=CustomDecoder)

print(type(person))  # Output: <class '__main__.Person'>
print(person.name)   # Output: Alice
print(person.birthdate)  # Output: 1990-05-15 00:00:00

Key Points

  • The object_hook method is called for each decoded object.
  • You can check for specific keys or patterns to determine how to decode the object.
  • Return the object as-is if no custom decoding is needed for that particular structure.
  • Custom decoders are useful for creating domain-specific objects directly from JSON data.

By using custom JSON decoders, you can seamlessly integrate JSON data into your Python application's object model, making data deserialization more flexible and aligned with your specific needs.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a custom JSON decoder for a weather data system. The decoder should convert JSON strings into WeatherData objects with specific attributes and conversions. Implement the following:

  1. Define a WeatherData class with attributes: location, temperature, humidity, and conditions.
  2. Create a custom JSONDecoder subclass that:
    • Converts temperature from Fahrenheit to Celsius, rounded to one decimal place.
    • Ensures humidity is represented as a percentage (e.g., 0.65 becomes 65%).
    • Capitalizes each word in the conditions string.
  3. Implement a function that takes a JSON string, uses the custom decoder to parse it, and returns a formatted string with the weather data.

The following input will be provided:


{"location": "new york", "temperature": 72, "humidity": 0.65, "conditions": "partly cloudy"}

Print the resulting formatted string in the following format:

"Location: [location], Temperature: [temp]°C, Humidity: [humidity], Conditions: [conditions]"

Try it yourself

Here's a suitable starter code for the challenge:

```python
import json

# Read input
json_string = input()

class WeatherData:
    def __init__(self, location, temperature, humidity, conditions):
        self.location = location
        self.temperature = temperature
        self.humidity = humidity
        self.conditions = conditions

class CustomJSONDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)

    def object_hook(self, dct):
        # TODO: Implement the custom decoding logic here
        pass

def parse_weather_data(json_string):
    # TODO: Implement the parsing function here
    pass

# TODO: Use the CustomJSONDecoder and parse_weather_data function to process the input

# Placeholder for the result
result = "Location: [location], Temperature: [temp]°C, Humidity: [humidity], Conditions: [conditions]"

# Output the result
print(result)
```

All lessons in Python JSON