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.delete(field=value)         # Delete items matching criteria, returns count
db.count(field=value)          # Count items (all, or matching criteria)
db.all()                       # Get all items
db.save()                      # Manual save (add and delete auto-save)

# Pythonic helpers
len(db)                        # Number of items
for item in db: ...            # Iterate over items
item in db                     # Membership test

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.delete(**kwargs) -> int              # Delete matching items, returns count, auto-saves
db.count(**kwargs) -> int               # Count all items, or those matching criteria
db.all() -> List[T]                     # Get all items
db.save() -> None                       # Manual save
len(db) -> int                          # Number of items
iter(db) -> Iterator[T]                 # Iterate over items
item in db -> bool                      # Membership test

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.4.0.tar.gz (19.0 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.4.0-py3-none-any.whl (10.7 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for typed_json_db-0.4.0.tar.gz
Algorithm Hash digest
SHA256 e30225055d3987002057bb9cacdddf56576c5d12f7d10f399d83ace312a87ea5
MD5 dca523335a4ab0a72f9a259caa3feadb
BLAKE2b-256 724e99aeb85ea3996b962ed97c89963b0cf7f849b4e945f3c9b0bcfc5e6146c7

See more details on using hashes here.

Provenance

The following attestation bundles were made for typed_json_db-0.4.0.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.4.0-py3-none-any.whl.

File metadata

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

File hashes

Hashes for typed_json_db-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 aa91f10bf4850cfaeb1d7631ebc3ec509ba3222711eea4128cb80e7a91636f85
MD5 a1816890b00caaa1ea8c39c29e60fc25
BLAKE2b-256 8c3488911824fd557a92fc33115b7c16fc9ac7588e5029eb1f5f0c462b8d4d48

See more details on using hashes here.

Provenance

The following attestation bundles were made for typed_json_db-0.4.0-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