Skip to main content

yet another dict library

Project description

pyaddict

PyPI version PyPI pyversions PyPI license

Description

Yet another python library to safely work with json data. It implements many useful features such as optional chaining, schema validation, type casting, safe indexing and default values.

Installation

pip install pyaddict

Usage

Accessing json data

from pyaddict import JDict

data = {
    "name": "John",
    "age": 30,
    "cars": [
        {"model": "BMW 230", "mpg": 27.5},
        {"model": "Ford Edge", "mpg": 24.1}
    ]
}

jdict = JDict(data).chain()  # enable chaining

jdict.expect("name", str)  # "John"
jdict.expect("name", int)  # TypeError: name is str, not int
jdict.expect("address", str)  # KeyError: key 'address' not found
jdict.expect("cars[0].mpg", float)  # 27.5 (because we enabled chaining)

# if we prefer None
jdict.optional_get("name", str)  # "John"
jdict.optional_get("name", int)  # None
jdict.optional_get("address", str)  # None
jdict.optional_get("address.street", str)  # KeyError: address not found
jdict.optional_get("address?.street", str)  # None
jdict.optional_get("cars[2].mpg", str)  # IndexError: out of range
jdict.optional_get("cars[2]?.mpg", str)  # None

# if we don't care whether it exists or not
jdict.ensure("name", str)  # "John"
jdict.ensure("name", int)  # 0, because name is not an int
jdict.ensure("age", int)  # 30
jdict.ensure("age", str)  # "", because age is not a string
jdict.ensure("address", str, "moon")  # "moon"
jdict.ensure("cars[].model", list)  # [ "BMW 230", "Ford Edge" ]
jdict.ensure("cars[0].mpg", float)  # 27.5
jdict.ensure("cars[0].mpg", int)  # 0, because cars[0].model is not an int

# or cast to the desired type
jdict.ensure_cast("cars[0].mpg", int) # 27

Similar rules apply when working with lists:

from pyaddict import JList

data = [{"name": "John", "age": 20}, {"name": "Jane", "age": 22}]

jlist = JList(data)

jlist.expect(0, dict)  # {"name": "John", "age": 20}
jlist.expect(0, int)  # TypeError: item is dict, not int
jlist.expect(2, dict)  # IndexError: out of range
jlist.expect("0.name", str)  # ValueError: invalid int

# if we enable chaining:
jlist = JList(data).chain()
jlist.expect("0.name", str)  # "John"
jlist.expect("[].name", list)  # ["John", "Jane"]

Validating json data

from pyaddict.schema import Anything, Array, Integer, Object, OneOf, String

schema = Object({
    "name": String(),
    "age": Integer().coerce(),
    "dogs": Array(
        OneOf(
            String(),
            Object({}, additional_properties=True)
        )
    ).min(1).optional(),
    "wildcard": Anything(),
    "valid": True
})

result = schema.validate({
    "name": "John",
    "age": 20.0,
    "wildcard": [1, 2, 3],
    "valid": True
})
result.valid  # True
result.unwrap()  # { "name": "John", "age": 20, "wildcard": [1, 2, 3], "valid": True }

result = schema.validate({
    "name": "John",
    "age": 5,
    "dogs": 1,
    "wildcard": True,
    "valid": True
})
result.valid  # False
result.unwrap()  # ValueError (invalid)
result.error  # 'dogs' should be list, not int

The library is fully typed and thus can be used with mypy & pylint. Check out the wiki for more information.

License

MIT

Author

davidohnee

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

pyaddict-2.1.0.tar.gz (14.1 kB view details)

Uploaded Source

Built Distribution

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

pyaddict-2.1.0-py3-none-any.whl (25.0 kB view details)

Uploaded Python 3

File details

Details for the file pyaddict-2.1.0.tar.gz.

File metadata

  • Download URL: pyaddict-2.1.0.tar.gz
  • Upload date:
  • Size: 14.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for pyaddict-2.1.0.tar.gz
Algorithm Hash digest
SHA256 9907528497f3c893d1d99450862a07f403e11068833af261a7d077bc1238a383
MD5 3a9c1756de1459bf8e97ce762dde14c6
BLAKE2b-256 476db12d75fa830bd01d6e6e3144e99b25d1d381c1f54857d73041488e0ad489

See more details on using hashes here.

File details

Details for the file pyaddict-2.1.0-py3-none-any.whl.

File metadata

  • Download URL: pyaddict-2.1.0-py3-none-any.whl
  • Upload date:
  • Size: 25.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for pyaddict-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e524e122fdf20976c40215fb70be244af82df38d6b6a340ed21a0cfe36d2cc58
MD5 718a8bf6bd223cce2d3d3672226d9f45
BLAKE2b-256 90b75c52e92260b41300217eebb24c56d89fe8224041e0fe65c5e61653c72a53

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