Skip to main content

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


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 hashes)

Uploaded Source

Built Distribution

elegant_json-0.1.0-py3-none-any.whl (7.7 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page