py-json-db (0.1.0rc1)

Published 2026-10-28 07:41:50 +00:00 by Andre-Capjoy

Installation

pip install --index-url  py-json-db

About this package

A PyMongo-style Python library that stores its data in one JSON file.

py-json-db

A small Python library that works like PyMongo, but keeps all data in one JSON file instead of a MongoDB server.

from py_json_db import Client

with Client("shop.json") as client:
    client.shop.items.insert_one({"name": "pen", "qty": 5})
  • Same API shape as PyMongo (reference: PyMongo 4.19.0, synchronous API): client.database.collection, insert_one, find, update_one, ...
  • No server and no dependencies. Standard library only; PyMongo and bson are not needed.
  • The data file is plain, readable JSON. Every change is saved before the call returns, and the file is replaced atomically, so a crash never leaves a half-written file.
  • For small data sets, scripts, tools and tests. Not for large data or many writers (see Limits).

Status: version 0.1.0, basic operations only. It is installed from the Forgejo package registry at git.capjoy.dev and is not on PyPI.

Requirements and install

Python 3.14 or newer.

From the Forgejo registry

The package is published to the PyPI registry of the Forgejo server. Give pip or uv its index URL:

pip install py-json-db --index-url https://git.capjoy.dev/api/packages/Andre-Capjoy/pypi/simple/
uv add py-json-db --index https://git.capjoy.dev/api/packages/Andre-Capjoy/pypi/simple/        # into a uv project
uv pip install py-json-db --index-url https://git.capjoy.dev/api/packages/Andre-Capjoy/pypi/simple/

This installs the latest stable release. A release candidate (published for each merge into next-release, for example 0.2.0rc1) is taken only when you ask for it: --pre for pip, --prerelease allow for uv. While no stable release exists, both tools take the release candidate without the flag.

The pip commands use --index-url, not --extra-index-url. Then PyPI is not asked for the name py-json-db, so nobody can win the choice by publishing a package with that name there. This is safe because the package has no dependencies. With uv, --index is searched before PyPI and uv stops at the first index that has the package, so PyPI is not asked for this name there either. Do not use --default-index: it would remove PyPI for the other dependencies of your project.

If the registry needs a login, add a line to ~/.netrc (and run chmod 600 ~/.netrc). The token needs the scope read:package. pip and uv both read this file, so the commands stay the same:

machine git.capjoy.dev login <your Forgejo user name> password <access token>

From a checkout of this repository

uv sync                # development install, includes the package
uv build               # builds dist/py_json_db-0.1.0-py3-none-any.whl
pip install dist/py_json_db-0.1.0-py3-none-any.whl

Quick start

from py_json_db import Client, DESCENDING
from py_json_db.errors import UnsupportedOperationError

with Client("shop.json") as client:        # the file is created if it does not exist
    items = client.shop.items              # database "shop", collection "items"

    items.insert_one({"name": "pen", "qty": 5})
    items.insert_many([{"name": "ink", "qty": 2}, {"name": "pad", "qty": 9}])

    for doc in items.find({"qty": {"$gte": 2}}, {"name": 1, "_id": 0}, sort=[("qty", DESCENDING)]):
        print(doc)                         # {'name': 'pad'}, {'name': 'pen'}, {'name': 'ink'}

    items.update_one({"name": "ink"}, {"$inc": {"qty": 10}})
    items.update_one({"name": "cap"}, {"$set": {"qty": 1}}, upsert=True)   # inserts "cap"
    items.delete_one({"name": "pad"})
    print(items.count_documents({}), items.distinct("name"))   # 3 ['pen', 'ink', 'cap']

    try:
        items.find_one({"name": {"$regex": "^p"}})
    except UnsupportedOperationError as error:
        print(error)                       # query operator '$regex' is not supported

A file that is not a valid database is never overwritten or repaired. Client("broken.json") raises CorruptFileError and leaves the file as it was.

What is supported

Objects: Client(path), Database, Collection, Cursor, ObjectId, and the constants ASCENDING and DESCENDING. Everything is imported from py_json_db; exceptions are in py_json_db.errors. ObjectId is the package's own class, not bson.ObjectId.

Client, database, collection: client.name and client["name"], list_database_names(), list_collection_names(), drop_database(), drop_collection(), collection.drop(), close() and with Client(...). Databases and collections are created when the first document is written.

Collection methods:

Group Methods
Insert insert_one, insert_many (ordered or unordered)
Read find, find_one, count_documents, distinct
Update update_one, update_many, replace_one, all with upsert=
Delete delete_one, delete_many

find returns a Cursor with skip(), limit(), sort(), next(), close() and iteration. It also takes projection, skip, limit and sort; give sort by keyword.

Filters: equality, dotted paths ("a.b", "tags.0"), $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $exists, $not, $and, $or, $nor.

Updates: $set, $unset, $inc, and whole-document replacement.

Values: None, bool, int, float, str, ObjectId, lists and nested documents. Other types such as datetime, bytes or Decimal raise InvalidDocument.

Anything else that PyMongo has and this package does not (for example $regex, $push, indexes, aggregate, find_one_and_update, async) raises UnsupportedOperationError with a message that names it, instead of silently doing something different.

How it differs from PyMongo

Most code written for PyMongo's basic operations should work after changing the import and creating the client from a file path instead of a URI. The differences are small but deliberate, and all are listed with their reasons in docs/differences-from-pymongo.md. The ones you are most likely to meet:

  • Client takes a file path, not a MongoDB URI.
  • _id can be an ObjectId, str, int or float, not an arbitrary value.
  • update_many is all or nothing: if one document causes an error, none is changed.
  • Documents are kept in insertion order, and that is the order of queries without a sort.
  • Query and update operators beyond the lists above are not provided.
  • UpdateResult and DeleteResult have no raw_result.

Limits

  • One client at a time. Use one Client per file, in one process. A second client or process does not see the first one's changes and can overwrite them. There is no file locking between processes.
  • Small data. Every write rewrites the whole file, so the cost grows with its size. There are no indexes, and queries scan the collection.
  • Strict on bad files. If the file is not valid (broken JSON, a document without _id, duplicate _ids, a name that cannot be opened, and so on), Client raises CorruptFileError. Fix or remove the file yourself.
  • Hand-edited files. The format is documented in REQ-003, but edit the file only while no client is using it.

Development

uv sync                                                  # install
uv run python -m unittest discover -s tests -t .         # test (standard library unittest)
uv build                                                 # build

The project follows docs/project-guideline.md; the plan is in docs/project-plan/:

  • stories/ and requirements/: what the package must do (REQ-001 to REQ-013).
  • tests/: the test specification (TC-001 to TC-013). Every case has exactly one test in tests/.
  • decisions/: design decisions (ADR-001, ADR-002).
  • traceability.md: which requirement, test and commit belong together.

Contributor and agent rules are in AGENTS.md.

Requirements

Requires Python: >=3.14
Details
PyPI
2026-10-28 07:41:50 +00:00
317
32 KiB
Assets (1)
Versions (1) View all
0.1.0rc1 2026-10-28