Skip to main content

Json Codec

It's a simple library to encode and decode json to strict python types using dataclasses and builtin python types.

Installation

pip install json-codec

poetry add json-codec

Usage

Parse a simple primitive type

from json_codec import decode
import json

assert decode(json.loads("true"), bool) is True
assert decode(json.loads("false"), bool) is False
assert decode(json.loads("null"), Optional[bool]) is None
assert decode(json.loads("1"), int) == 1
assert decode(json.loads("1"), Decimal) == Decimal("1")
assert decode(json.loads('"1.1"'), Decimal) == Decimal("1.1")
assert decode(json.loads('"1.1"'), float) == 1.1
assert decode(json.loads('"1.1"'), str) == "1.1"

assert decode(json.loads('[1,1]'), List[int]) == [1, 1]

Parse a dataclass

from dataclasses import dataclass
from json_codec import decode
import json

@dataclass(frozen=True)
class User:
    name: str
    age: int

assert decode({"name": "John", "age": 30}, User) == User(name="John", age=30)


@dataclass
class Dummy:
    text_list: List[str]
    text_dict: Dict[str, Decimal]
    optional_text: Optional[str]

dummy_json_text = """
{
    "text_list": ["a", "b", "c"],
    "text_dict": {
        "a": 1.0,
        "b": 2,
        "c": "3.3",
        "d": 2.2
    },
    "optional_text": "hello"
}
"""

dummy_json = json.loads(dummy_json_text)

parsed = decode(dummy_json, Dummy)

assert parsed.text_list == ["a", "b", "c"]
assert parsed.text_dict["a"] == Decimal("1.0")
assert parsed.text_dict["b"] == Decimal("2.0")
assert parsed.text_dict["c"] == Decimal("3.3")
assert parsed.text_dict["d"].quantize(Decimal("1.0")) == Decimal("2.2")
assert parsed.optional_text == "hello"

Parse a dataclass with a nested dataclass

from dataclasses import dataclass
from json_codec import decode
import json

 @dataclass
class NestedDummy:
    text: str
    number: Decimal

    boolean: bool

@dataclass
class Dummy:
    text_list: List[str]
    text_dict: Dict[str, Decimal]
    nested: NestedDummy

dummy_json_text = """
{

    "text_list": ["a", "b", "c"],
    "text_dict": {
        "a": 1.0,
        "b": 2,
        "c": "3.3",
        "d": 2.2
    },
    "nested": {
        "text": "hello",
        "number": 1.1,
        "boolean": true
    }
}
"""

dummy_json = json.loads(dummy_json_text)

parsed = decode(dummy_json, Dummy)

assert parsed.text_list == ["a", "b", "c"]
assert parsed.text_dict["a"] == Decimal("1.0")
assert parsed.text_dict["b"] == Decimal("2.0")
assert parsed.text_dict["c"] == Decimal("3.3")
assert parsed.text_dict["d"].quantize(Decimal("1.0")) == Decimal("2.2")
assert parsed.nested.text == "hello"
assert parsed.nested.number.quantize(Decimal("1.0")) == Decimal("1.1")
assert parsed.nested.boolean is True

Parse a newtype

from json_codec import decode
from typing import NewType
import json

UserId = NewType("UserId", int)

assert decode(json.loads("1"), UserId) == UserId(1)
assert isinstance(decode(json.loads("1"), UserId), int)

Release files for json-codec 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for json-codec 0.3.0
File Size Uploaded
json_codec-0.3.0.tar.gz 8.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for json-codec 0.3.0
File Interpreter ABI Platform
json_codec-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 22.5 kB

Release files / json_codec-0.3.0.tar.gz

Download URL json_codec-0.3.0.tar.gz
Size 8.9 kB
Tags Source
SHA-256 checksum
How to use checksums
3ab669f81bf025c9567c04c47daecae0ee45061e929ac6359a8230664cde1240
BLAKE2b-256 checksum
How to use checksums
5a351aec234d8dbe519aff7d68ac455c52cc8f6e8651788ff0fd141c2effe4bf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.3.2 CPython/3.7.10 Linux/5.15.90.1-microsoft-standard-WSL2

Release files / json_codec-0.3.0-py3-none-any.whl

Download URL json_codec-0.3.0-py3-none-any.whl
Size 13.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9e9ce1c6e229c9080a4c8e5df64df3a84a4bffd290e5d10907a16c7860ec0011
BLAKE2b-256 checksum
How to use checksums
82056a64a0406acdc8fc27ceaf9837ba8689a3308873af4599ae7d898c930102
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.3.2 CPython/3.7.10 Linux/5.15.90.1-microsoft-standard-WSL2

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files

0.2.0

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page