Skip to main content

JSON Decoder and Encoder with type information.

Project description

StrongJson

PyPI Build Status Binder

A more faithful python json encoder/decoder.

Install

pip install strong_json

or directly from this repository

pip install git+git://github.com/piti118/strong-json.git

Features

In addition to the standard json.dumps/loads, this module offer the following additonal behavior.

  • Simple interface to allow class to dump to json.

    • class User(ToJsonable):
          def __init__(self, first, last):
              self.first = first
              self.last = last
      
  • Preserve type information.

    • User('f', 'l') -> {'__type__': 'User', 'first':'f', 'last':'l'}
  • More faithful dictionary dumps/loads

    • Treat dictionary as OrderedDictionary when encode. See Python 3.6 Release Note.
      • {'a':'b', 'c':'d'} ->
        {
            '__type__':'dict'
            '__data__':[
                {'key': 'a', 'value': 'b'},
                {'key': 'c', 'value': 'd'},
            ]
        }
        
      • Decoder will accept both traditional form({'a':'b','c':'d'}) and the form above.
    • Allow any hashable object as key
      • {User('f', 'l'): 1, User('a','b'):2} ->
        {
            '__type__': 'dict'
            '__data__': [
                {
                    'key': {'__type__': 'User', 'first': 'f', 'last':'l'}, 
                    'value: 1
                },
                {
                    'key': {'__type__': 'User', 'first': 'a', 'last':'b'}, 
                    'value: 2
                }
            ]
        }        
        
  • Distinguish tuple from List

    • [1,2,3] -> [1,2,3]
    • (1,2,3) -> {'__type__':'tuple', '__data__':[1,2,3]}
  • Custom class decoder whitelist via class_map

    • from strong_json import StrongJson
      s = {'__type__': 'User', 'first':'f', 'last':'l'}
      class_map = {'User', User}
      custom_json = StrongJson(class_map=class_map)
      custom_json.from_json(s)
      
    • By default, strong json pass all the argument by name to the constructor.
    • You could also override StrongJson or implement interface FromJsonable for custom decoder.
    • You could also use strong_json.ClassMapBuilder to save some typing.
  • Support for date and datetime.

    • datetime.date(2019,8,23) ->
    {
        '__type__': 'date', 
        'year': 2019, 
        'month': 8, 
        'day': 23
    }
    
  • Support for Enum.

    • class Color(Enum):
        RED='redd'
        BLUE='blueee'
      strong_json.to_json(Color.RED)
      
      ->
      {'__type__': 'Color' '__data__':'RED'}
      

Basic Usage

Binder

From Object to JSON

Builtin Object

from strong_json import strong_json
obj = {'a': [1,2,3], 'b':[2,3,4]}
s = strong_json.to_json(obj)

# if you want indentation you could do
s_indent = strong_json.to_json(obj, indent=2)

Custom Class

SimpleClass

Custom class works out of the box

from strong_json import strong_json

class SimpleClass:
    def __init__(self, msg):
        self.msg = msg

obj = SimpleClass('hello')
s = strong_json.to_json(object)

which produce json of the form

{
  "__type__": "SimpleClass",
  "msg": "hello"
}

Custom Encoder.

If you don't like the default class encoder you can create new one by implementing ToJsonable interface.

from strong_json import strong_json, ToJsonable

class User(ToJsonable):
    def __init__(self, first, last):
        self.first = first
        self.last = last

    # this is where the magic happens.
    def to_json_dict(self, encoder: StrongJson) -> Dict[str, JSONPrimitive]:
        return {
            '__type__': 'User',
            'first': encoder.to_json_dict(self.first),
            'last': encoder.to_json_dict(self.last),
            'full_name': encoder.to_json_dict(f"{self.first} {self.last}")
        }

obj = User('hello', 'world')
s = strong_json.to_json(object)

which produces json of the form

{
  "__type__": "User",
  "first": "hello",
  "last": "world",
  "full_name": "hello_world"
}

From JSON to object

Builtin Object

from strong_json import strong_json
s = """{'a': 'b', 'c':'d'}"""
obj = strong_json.from_json(s)

Custom Class

from strong_json import StrongJson

class User: # it doesn't have to be ToJsonable
    def __init__(self, first, last):
        self.first = first
        self.last = last

s = """
{
    '__type__': 'User',
    'first': 'hello',
    'last': 'world'
}
"""
class_map = {'User': User}
custom_json = StrongJson(class_map=class_map)
obj = custom_json.to_json(s, class_map)

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

strong_json-1.0.4.tar.gz (11.1 kB view details)

Uploaded Source

Built Distribution

strong_json-1.0.4-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file strong_json-1.0.4.tar.gz.

File metadata

  • Download URL: strong_json-1.0.4.tar.gz
  • Upload date:
  • Size: 11.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.7.3

File hashes

Hashes for strong_json-1.0.4.tar.gz
Algorithm Hash digest
SHA256 fb815de772f7d152f6304490146db4d2c38383a9994a7cd30f8c51122b76fd7c
MD5 dbb7064181f4f0fb85ee1e69d9d863d7
BLAKE2b-256 c72cee89700192d579dd23051800bec59e61795f0651133c1af414b6b2f41976

See more details on using hashes here.

File details

Details for the file strong_json-1.0.4-py3-none-any.whl.

File metadata

  • Download URL: strong_json-1.0.4-py3-none-any.whl
  • Upload date:
  • Size: 7.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.7.3

File hashes

Hashes for strong_json-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 d609b504fd9a48742ccc09d7e006b21a79e0e9305785635613cb9198a91034bf
MD5 a8fd5523bdf31f9625f9485662974b12
BLAKE2b-256 13ea9d7627afbef937c95c33615af654902e154ba011598874ac5ee0c9324e1b

See more details on using hashes here.

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