Skip to main content

A simple JSON-based database for Python applications

Project description

Typed JSON DB

PyPI - Version codecov

A lightweight, type-safe JSON-based database for Python applications using dataclasses. Choose between two database types based on your needs:

  • JsonDB - Simple storage with basic operations (add, find, all)
  • IndexedJsonDB - Advanced storage with primary key support (get, update, remove) and indexing

Features

  • 🚀 Type-safe with full generic type support
  • 📁 File-based JSON storage - easy to inspect and backup
  • 🔍 Query support using attribute-based queries
  • Two database types for different use cases
  • Fast lookups with automatic primary key indexing
  • 📦 Zero dependencies required
  • 🆔 UUID support and nested dataclasses

Installation

pip install typed-json-db

Quick Start

from dataclasses import dataclass
from enum import Enum
import uuid
from pathlib import Path
from typed_json_db import JsonDB, IndexedJsonDB

@dataclass
class User:
    id: uuid.UUID
    name: str
    email: str
    status: str
    age: int

# Simple database - basic operations only
simple_db = JsonDB(User, Path("users.json"))
simple_db.add(user)
users = simple_db.find(status="active")
all_users = simple_db.all()

# Indexed database - full CRUD with fast lookups
indexed_db: IndexedJsonDB[User, uuid.UUID] = IndexedJsonDB(
    User, Path("users.json"), primary_key="id"
)
indexed_db.add(user)
user = indexed_db.get(user_id)        # Fast O(1) lookup
indexed_db.update(modified_user)      # Update by primary key
indexed_db.remove(user_id)            # Remove by primary key

Database Types

JsonDB - Simple Storage

Use JsonDB when you need basic storage without primary key constraints:

db = JsonDB(User, Path("users.json"))

# Available operations
db.add(item)                   # Add new items
db.find(field=value)           # Query by any field  
db.all()                       # Get all items
db.save()                      # Manual save (auto-saves on add)

IndexedJsonDB - Advanced Storage

Use IndexedJsonDB when you need primary key support and fast lookups:

db: IndexedJsonDB[User, uuid.UUID] = IndexedJsonDB(
    User, Path("users.json"), primary_key="id"
)

# All JsonDB operations plus:
db.get(primary_key)            # Fast O(1) primary key lookup
db.update(item)                # Update existing item by primary key
db.remove(primary_key)         # Remove by primary key
db.find(id=primary_key)        # Optimized primary key search

Key Benefits:

  • Fast lookups - O(1) primary key operations via automatic indexing
  • 🔒 Uniqueness enforcement - Primary key values must be unique
  • 🎯 Type safety - Generic types for both data and primary key
  • 🔄 Auto-indexing - Index maintained automatically on all operations

API Reference

Common Methods (Both Classes)

db.add(item: T) -> T                    # Add new item, auto-saves
db.find(**kwargs) -> List[T]            # Query by any field  
db.all() -> List[T]                     # Get all items
db.save() -> None                       # Manual save

IndexedJsonDB Additional Methods

db.get(key: PK) -> Optional[T]          # Fast O(1) lookup by primary key
db.update(item: T) -> T                 # Update by primary key, auto-saves  
db.remove(key: PK) -> bool              # Remove by primary key, auto-saves

Examples

Type Safety with UUIDs

import uuid
from dataclasses import dataclass

@dataclass
class User:
    id: uuid.UUID
    name: str
    email: str

# Type-safe primary key operations  
db: IndexedJsonDB[User, uuid.UUID] = IndexedJsonDB(User, Path("users.json"), primary_key="id")

user_id = uuid.uuid4()
db.add(User(id=user_id, name="Alice", email="alice@example.com"))

# IDE provides type checking and autocomplete
user = db.get(user_id)  # ✅ Expects UUID
# user = db.get("string")  # ❌ Type error

Automatic Timestamps

Use Timestamped base class for automatic timestamp management:

from typed_json_db import Timestamped

@dataclass
class Article(Timestamped):
    id: uuid.UUID
    title: str
    # created_at and updated_at fields inherited automatically

db = IndexedJsonDB(Article, Path("articles.json"), primary_key="id")
article = Article(id=uuid.uuid4(), title="Hello")
db.add(article)  # created_at and updated_at set automatically
db.update(article)  # updated_at timestamp refreshed

Automatic Type Conversion

Supports automatic serialization of:

  • UUID, datetime, date objects
  • Enums and nested dataclasses
  • Lists of dataclasses
from datetime import datetime
from enum import Enum

class Status(Enum):
    ACTIVE = "active"
    INACTIVE = "inactive"

@dataclass  
class Order:
    id: uuid.UUID
    created_at: datetime
    status: Status
    items: List[Product]  # Nested dataclasses

# All types automatically converted to/from JSON
db: IndexedJsonDB[Order, uuid.UUID] = IndexedJsonDB(Order, Path("orders.json"), primary_key="id")

Performance

  • IndexedJsonDB: O(1) primary key operations via automatic indexing
  • JsonDB: O(n) linear search for all operations
  • Auto-indexing: Index maintained automatically on all operations
  • Memory efficient: Index rebuilt on database load

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

typed_json_db-0.3.1.tar.gz (17.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

typed_json_db-0.3.1-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

Details for the file typed_json_db-0.3.1.tar.gz.

File metadata

  • Download URL: typed_json_db-0.3.1.tar.gz
  • Upload date:
  • Size: 17.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for typed_json_db-0.3.1.tar.gz
Algorithm Hash digest
SHA256 7631168f725c5ce53044f0f17ae3f77aefc7def26790e6b30f2776c16fb26196
MD5 61190b23ba27fdd9f2ee89f9adc3bae5
BLAKE2b-256 892050e31ae45b985e9c1ac57cea95fe40437d3cd9533a54d24316ef317888f3

See more details on using hashes here.

Provenance

The following attestation bundles were made for typed_json_db-0.3.1.tar.gz:

Publisher: deploy-pypi.yml on frangiz/typed-json-db

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file typed_json_db-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: typed_json_db-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 10.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for typed_json_db-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 58a55a15027bf0cebce776cbefce12891bbb8379b3bbbd04043b733f9c8eb458
MD5 db8180c5373df242285593f24f662694
BLAKE2b-256 5970306932e7e3160feaf8e0d801307aac25234eece9da7ba5cca44523a3bbf6

See more details on using hashes here.

Provenance

The following attestation bundles were made for typed_json_db-0.3.1-py3-none-any.whl:

Publisher: deploy-pypi.yml on frangiz/typed-json-db

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page