Skip to main content

JSON/JSON5 file handling with dataclass support

Project description

aka_json

A Python module for robust JSON/JSON5 file handling with datataсlass support, custom encoders/decoders, and enhanced error handling.


Features

  • JSON & JSON5 Support: Read/write standard JSON and relaxed JSON5 files (comments, trailing commas).
  • Dataclass Integration: Seamless serialization/deserialization using dacite.
  • Extended Type Support: Auto-handling of datetime, date, time, and bytes objects.
  • Validation & Safety: File extension checks, content type enforcement (dict/list), and encoding control.
  • Error Handling: Custom exceptions (FileExtensionError, ContentTypeError, FileOpenError).
  • Formatting Control: Customize indentation, ASCII encoding, key sorting, and file modes.
  • Context Managers: Safe file handling using with statements.

Installation

Dependencies

Use this if you clone repository

pip install dacite json5

Module Setup

Install via PyPi

pip install aka_json

Or clone the repository:

git clone https://github.com/your-repo/aka_json.git
cd aka_json

Import classes directly into your project.


Quick Start

Basic JSON Operations

from aka_json import JsonFile

# Create and write to a JSON file
with JsonFile("data.json", create_file=True) as file:
    file.write({"name": "Alice", "age": 30})

# Read data
data = JsonFile("data.json").read()
print(data)  # Output: {'name': 'Alice', 'age': 30}

Dataclass Serialization

from dataclasses import dataclass
from aka_json import JsonFile

@dataclass
class User:
    name: str
    age: int

# Write dataclass object
user = User("Bob", 25)
with JsonFile("user.json", create_file=True) as file:
    file.write(user)

# Read as dataclass
loaded_user = JsonFile("user.json").read_as_dataclass(User)
print(loaded_user)  # Output: User(name='Bob', age=25)

JSON5 File Handling

from aka_json import Json5File

# Write to JSON5 (supports relaxed syntax)
with Json5File("config.json5", create_file=True) as file:
    config = {
        "host": "localhost",  # Example comment
        "port": 8080,
    }
    file.write(config)

Core Classes

Class Description
SimpleJsonFile Base JSON handler (open/read/write/remove).
JsonFile Adds dataclass support to SimpleJsonFile.
SimpleJson5File Base JSON5 handler with relaxed syntax support.
Json5File Extends SimpleJson5File with dataclass integration.

Key Methods

Common Operations

  • open(create_file=False): Open file (create if missing).
  • close(remove_file=False): Close file (optionally delete it).
  • read(): Return JSON data as dict/list.
  • write(content): Write data to file (supports dataclasses).
  • read_as_dataclass(cls): Deserialize JSON into a dataclass object.
  • clear(): Reset file to empty dict/list.

Configuration

file.set_options(
    content_type=ContentType.LIST,  # Dict/List structure
    coding=Coding.UTF8,            # Encoding
    indent=4,                      # Indentation
    sort_keys=True                  # Sort JSON keys
)

Constants

ContentType

  • DICT: Treat file as dictionary (default).
  • LIST: Treat file as list.

FileMode

  • Modes: READ, WRITE, APPEND, and binary variants.

Coding

  • Encodings: UTF8, ASCII, GBK, and 10+ others.

Error Handling

from aka_json import FileExtensionError, ContentTypeError

try:
    # Attempt to open non-JSON file
    file = JsonFile("data.txt")
except FileExtensionError as e:
    print(f"Error: {e}")  # "File data.txt has incorrect extension"

License

MIT License. See LICENSE 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

aka_json-1.0.1.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

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

aka_json-1.0.1-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

Details for the file aka_json-1.0.1.tar.gz.

File metadata

  • Download URL: aka_json-1.0.1.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for aka_json-1.0.1.tar.gz
Algorithm Hash digest
SHA256 1f1cc13d2a0149781af79cfe20e1000b17beeaaf91dff31b6ba0915f31c7356b
MD5 127a783c1f189fbc3fa054aaf28bf963
BLAKE2b-256 57a355fb1d27248ba899fd5fe2ff559572b81dba3ce5b22d5ac8901d6fa55629

See more details on using hashes here.

File details

Details for the file aka_json-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: aka_json-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 12.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for aka_json-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 4e6d8eb2650f4d589f82291562b8209d8721e0acb0406596b2f6878b121ef5bd
MD5 89ecb280f765dd5a0be0543706be67ff
BLAKE2b-256 84b70db6f938f7ac32021e3934723602c254c696ac6082d9dbc3eda535ff9029

See more details on using hashes here.

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