How I can create Python class from JSON object?

Creating Python classes from JSON objects can be accomplished using the python-jsonschema-objects library, which is built on top of jsonschema. This library provides automatic class-based binding to JSON schemas for use in Python.

Installing the Required Library

First, install the python-jsonschema-objects library ?

pip install python-jsonschema-objects

Defining a JSON Schema

Let's start with a sample JSON schema that defines the structure of a Person object ?

schema = '''{
    "title": "Example Schema",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        },
        "dogs": {
            "type": "array",
            "items": {"type": "string"},
            "maxItems": 4
        },
        "gender": {
            "type": "string",
            "enum": ["male", "female"]
        },
        "deceased": {
            "enum": ["yes", "no", 1, 0, "true", "false"]
        }
    },
    "required": ["firstName", "lastName"]
}'''

print("Schema defined successfully")
Schema defined successfully

Converting Schema to Python Class

Now we can convert the JSON schema into a Python class using the ObjectBuilder ?

import python_jsonschema_objects as pjs

# Build the class from schema
builder = pjs.ObjectBuilder(schema)
ns = builder.build_classes()

# Get the generated class
Person = ns.ExampleSchema

# Create an instance
jack = Person(firstName="Jack", lastName="Sparrow")

print(f"Name: {jack.firstName} {jack.lastName}")
print(f"Age: {jack.age}")

Working with Class Instances

The generated class behaves like a regular Python class with additional validation ?

# Setting valid properties
jack.age = 30
jack.gender = "male"
jack.dogs = ["Buddy", "Max"]

print(f"Updated Person: {jack.firstName} {jack.lastName}, Age: {jack.age}")
print(f"Gender: {jack.gender}")
print(f"Dogs: {jack.dogs}")

Schema Validation

The library automatically validates data against the schema constraints ?

# This will raise a validation error
try:
    jack.age = -2  # Violates minimum: 0 constraint
except Exception as e:
    print(f"Validation Error: {e}")

# This will also raise an error
try:
    jack.gender = "other"  # Not in enum values
except Exception as e:
    print(f"Validation Error: {e}")

Key Benefits

Feature Benefit
Automatic Validation Ensures data integrity based on schema
Type Safety Prevents invalid data assignments
IDE Support Better autocompletion and error detection
Documentation Schema serves as documentation

Alternative Approach Using dataclasses

For simpler cases, you can also use Python's built-in dataclasses ?

import json
from dataclasses import dataclass
from typing import List, Optional

@dataclass
class Person:
    firstName: str
    lastName: str
    age: Optional[int] = None
    dogs: Optional[List[str]] = None
    gender: Optional[str] = None

# Create from JSON
json_data = '{"firstName": "John", "lastName": "Doe", "age": 25}'
person_dict = json.loads(json_data)
person = Person(**person_dict)

print(f"Person: {person.firstName} {person.lastName}, Age: {person.age}")
Person: John Doe, Age: 25

Conclusion

The python-jsonschema-objects library provides powerful automatic validation and class generation from JSON schemas. For simpler use cases, Python's built-in dataclasses offer a lightweight alternative for creating classes from JSON data.

Updated on: 2026-03-24T19:49:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements