jsonobject

2.3.1 · active · verified Thu Apr 16

jsonobject is a Python library for handling deeply nested JSON objects as well-schema'd Python objects. It provides a declarative way to define data models for JSON structures, facilitating easy serialization and deserialization between Python objects and JSON. Maintained by Dimagi, it is currently at version 2.3.1 and typically follows an active release cadence.

Common errors

Warnings

Install

Imports

Quickstart

Define a `JsonObject` subclass with various `Property` types, instantiate objects, and serialize them to JSON. Also demonstrates deserialization from a dictionary.

import datetime
from jsonobject import JsonObject, StringProperty, BooleanProperty, DateTimeProperty, ListProperty

class User(JsonObject):
    username = StringProperty(required=True)
    name = StringProperty()
    active = BooleanProperty(default=False)
    date_joined = DateTimeProperty()
    tags = ListProperty(str)

# Create an object
user1 = User(
    name='Jane Doe',
    username='janedoe',
    date_joined=datetime.datetime.utcnow(),
    tags=['developer', 'python']
)

print(f"User object: {user1}")
print(f"User to JSON: {user1.to_json()}")

# Create from existing JSON
json_data = {
    'username': 'alice',
    'name': 'Alice Smith',
    'active': True,
    'date_joined': '2023-01-15T10:30:00Z',
    'tags': ['tester']
}
user2 = User(json_data)
print(f"User from JSON: {user2}")
print(f"Is user2 active? {user2.active}")

view raw JSON →