Deal with JSON in an elegant way
Project description
elegant-json
Deal with JSON files elegantly.
Warning
elegant-json
is Work in Progress!
Installation
- use pip
pip install elegant-json
- clone repo
git clone https://github.com/hanjinliu/elegant-json
Motivation
Suppose you have a JSON file in the following format.
{
"title": "Title",
"data": {
"last modified": "2022.06.01",
"values": [0, 1, 2, 3]
}
}
What would you do?
Conventional way
import json
with open("path/to/json") as f:
js = json.load(f)
# `js` is a nested dictionary
js["title"]
js["data"]["last modified"]
js["data"]["values"][2]
This is terrible.
✗ typing
✗ missing values
✗ readability
In this module
Copy and paste the json text and substitute values you want with Attr
objects.
from elegant_json import JsonClass, Attr
# define a class with a json template
class C(JsonClass):
__json_template__ = {
"title": Attr(),
"data": {
"last modified": Attr(name="last_modified"),
"values": Attr()
}
}
title: str
last_modified: str
values: list[int]
c = C.load("path/to/json") # or from a dict >>> c = C(js)
# now all the attributes can be accessed like below
c.title
c.last_modified
c.values[2]
Other helper functions
-
isformatted
This function checks if a dictionary is in the given format
from elegant_json import isformatted dict0 = { "title": "Formatted data", "data": { "last modified": "yyyy.mm.dd", "values": [] } } isformatted(dict0, C) # True dict1 = { "title": "Wrong data", "data": { "a": 0, "b": 2, } } isformatted(dict1, C) # False
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
elegant-json-0.1.0.tar.gz
(6.5 kB
view details)
Built Distribution
File details
Details for the file elegant-json-0.1.0.tar.gz
.
File metadata
- Download URL: elegant-json-0.1.0.tar.gz
- Upload date:
- Size: 6.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.7.0 importlib_metadata/4.8.2 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.63.0 CPython/3.9.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | efdd48fdde37181d87584074844f1d985d8a5f1cc4dfb6b1b226b5ae1e437ba3 |
|
MD5 | 018d5653c90bdc6d18e08f79ab0082f9 |
|
BLAKE2b-256 | a6d194216b42ec1e437d72824267ed34581204e87915548f44293fb810182e7f |
File details
Details for the file elegant_json-0.1.0-py3-none-any.whl
.
File metadata
- Download URL: elegant_json-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.7.0 importlib_metadata/4.8.2 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.63.0 CPython/3.9.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7fde6de32a23fbbb1a9696a162af0e3c64390f1eea52ddcf210489362d688a5e |
|
MD5 | c347e501ee4c0414ebb071bac7bd0669 |
|
BLAKE2b-256 | 283be65cd6b663944a6e279b67ab604ea8597d516b981aa26a0e34575bb1aab0 |