Skip to main content

JavaScript-like Python dictionary

Project description

JDICT

JavaScript-like Python dictionary. For background and design description look at this Medium article.

Installation

Use the package manager pip to install jdict from the PyPi site:

pip3 install pyjdict

The package name is pyjdict, but the module name is jdict.

What is jdict?

Let's imagine we have some deeply nested json structure as following(this is not really deep, but it's enough for the sake of example):

    {
        "status": True,
        "data": {
            "file": {
                "url": {
                    "short": "https://anonfiles.com/t3l5S2Gex3",
                    "full": "https://anonfiles.com/t3l5S2Gex3/test_txt",
                },
                "metadata": {
                    "size": {"bytes": 19, "readable": "19 B"},
                    "name": "test_txt",
                    "id": "t3l5S2Gex3",
                },
            }
        },
    }

Now, you need get the id of this data, yes you are going to feel the pain as: this_awesome_json["data"]["file"]["metadata"]["id"].

But how about accessing this id as: this_awesome_json.data.file.metadata.id? Even for loop and assign values directly using .[dot] access?

That's where the jdict shines. It is lightweight, nearly zero cost library converts your dictionaries to special jdict type and you are ready to go.

Usage

Now let's build small script to show the jdict. We are going to use anonymous file upload public API.

import requests
import json

from jdict import jdict, set_json_decoder


# Send post request and upload the test.txt file - you can create one
def _upload_file() -> str:
    file = {"file": open("test.txt", "rb")}
    result = requests.post("https://api.anonfiles.com/upload", files=file)
    result_dict = result.json()
    # Feel the pain here
    return result_dict["data"]["file"]["metadata"]["id"]

# Send get request and get back the json information about the uploaded file
def _get_file_info() -> dict:
    url = f"https://api.anonfiles.com/v2/file/{_upload_file()}/info"
    return requests.get(url).json()

# Change codec to use jdict
def _convert_to_jdict() -> jdict:
    set_json_decoder(json)
    return _get_file_info()

The killer point here is to change the codec and then convert our dictionary to jdict.

If you are using simplejson, just pass it as pyjdict.set_codec(simplejson), it will do the same trick.

Great, now we are ready to use it:

if __name__ == "__main__":
    """
    Sample data:
    {
        "status": True,
        "data": {
            "file": {
                "url": {
                    "short": "https://anonfiles.com/t3l5S2Gex3",
                    "full": "https://anonfiles.com/t3l5S2Gex3/test_txt",
                },
                "metadata": {
                    "size": {"bytes": 19, "readable": "19 B"},
                    "name": "test_txt",
                    "id": "t3l5S2Gex3",
                },
            }
        },
    }
    """
    data = _convert_to_jdict()
    # Get the id:
    print("ID: ", data.data.file.metadata.id)
    # Use in for loop:
    for key, value in data.data.file.metadata.items():
        print(key, value)
    # Set the id:
    data.data.file.metadata.id = "MYID"
    print("ID: ", data.data.file.metadata.id)

Sample output:

$ python3 main.py

ID:  h8p2SbGfx2
size {'bytes': 19, 'readable': '19 B'}
name test_txt
id h8p2SbGfx2
ID:  MYID

Patching

The next crucial feature is to ability to path core libraries with jdict.

Just think about the boto3 library, with AWS you may encounter really deeply nested json structures, with jdict you can access those nested values with .[dot] notation as well.

By patching botocore.parsers you gain really powerful tooling to work with:

import os
import boto3
import jdict

jdict.patch_module('botocore.parsers')

def test_library():
    response = boto3.client('s3').list_buckets()
    assert(response.Buckets == response['Buckets'])
    return 'OK'

Just keep in mind that you need to have valid AWS credentials to run this code

License

MIT License, Copyright (c) 2021-2022 BST LABS. See LICENSE file.

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

pyjdict-1.0.6.tar.gz (12.9 kB view details)

Uploaded Source

Built Distribution

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

pyjdict-1.0.6-py3-none-any.whl (6.6 kB view details)

Uploaded Python 3

File details

Details for the file pyjdict-1.0.6.tar.gz.

File metadata

  • Download URL: pyjdict-1.0.6.tar.gz
  • Upload date:
  • Size: 12.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.27.1

File hashes

Hashes for pyjdict-1.0.6.tar.gz
Algorithm Hash digest
SHA256 b363e6ba25830fc57d0387c2c7ef025ea6c5ad65e75da7c7828d557c36d056e6
MD5 0a1b1e0c7162f7cc9796f549c7c73efa
BLAKE2b-256 71812bc6742f2ea9e92a3854cd8ad86f224ff2ebd77b00c58fced34bfa1226a5

See more details on using hashes here.

File details

Details for the file pyjdict-1.0.6-py3-none-any.whl.

File metadata

  • Download URL: pyjdict-1.0.6-py3-none-any.whl
  • Upload date:
  • Size: 6.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.27.1

File hashes

Hashes for pyjdict-1.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 79994553a1db60668c3fb5ba8a3d21fd7e56af7d15b0708b9ae08b6927594d10
MD5 a44d54aa175b39b29b2e4282e94a8eaf
BLAKE2b-256 395e3ec42419cd0a408a11b2fb3240e07c8e481c5abef397dc5dd5e29f97c273

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