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

pip install dacite json5

Module Setup

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.0.tar.gz (11.9 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.0-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: aka_json-1.0.0.tar.gz
  • Upload date:
  • Size: 11.9 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.0.tar.gz
Algorithm Hash digest
SHA256 dc4ad3cdc207787844529912ba5263caf288e4e30ba762c1a890cbb14a1769ca
MD5 cd2af715508d2bf50d004445f444e3c1
BLAKE2b-256 5d951921bd1dd38fcd30d53e02bf0e4e4d52d036b619d06ca88b8dd28d5734ef

See more details on using hashes here.

File details

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

File metadata

  • Download URL: aka_json-1.0.0-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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 80a33c94aef36d8c6f8dae97838c8a3c8f77abd7b0673625790b5812c86bdcb4
MD5 d8b2fa25ccfb746e6be42c5e5db00f21
BLAKE2b-256 34c6d18d4ff6f0e3f0f2ebda12fa4ab702dd9eefcde2ae64ad15449bff775c55

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