Marshall python objects to and from JSON

Overview

Pymarshaler - Marshal and Unmarshal Python Objects

Disclaimer

This tool is in no way production ready

About

Pymarshaler allows you to marshal and unmarshal any python object directly to and from a JSON formatted string.

Pymarshaler takes advantage of python's new typing support. By reading class init param types, we are able to walk down nested JSON structures and assign appropriate values.

Basic Usage

Declare a class with typing information

Note, we can use regular old classes as long as their init methods are annotated properly, but it's preferable to use dataclasses whenever possible

from dataclasses import dataclass

@dataclass
class Test:
    
    name: str

That's it! We can now marshal, and more importantly, unmarshal this object to and from JSON.

from pymarshaler.marshal import Marshal
import json

test_instance = Test('foo')
blob = Marshal.marshal(test_instance)
print(blob.decode())
>>> '{name: foo}'

marshal = Marshal()
result = marshal.unmarshal(Test, json.loads(blob))
print(result.name)
>>> 'foo'

We also use marshal.unmarshal_str(cls, str) if we want to unmarshal directly from the blob source.

This is a pretty trivial example, lets add in a nested class

from dataclasses import dataclass

@dataclass
class StoresTest:
    
    test: Test

    
stores_test = StoresTest(Test('foo'))
blob = marshal.marshal(stores_test)
print(blob)
>>> '{test: {name: foo}}'

result = marshal.unmarshal(StoresTest, json.loads(blob))
print(result.test.name)
>>> 'foo'

As you can see, adding a nested class is as simple as as adding a basic structure.

Pymarshaler will fail when encountering an unknown field by default, however you can configure it to ignore unknown fields

from pymarshaler.marshal import Marshal 
from pymarshaler.arg_delegates import ArgBuilderFactory

marshal = Marshal()
blob = {'test': 'foo', 'unused_field': 'blah'}
result = marshal.unmarshal(Test, blob)
>>> 'Found unknown field (unused_field: blah). If you would like to skip unknown fields create a Marshal object who can skip ignore_unknown_fields'

marhsal = Marshal(ignore_unknown_fields=True)
result = marshal.unmarshal(Test, blob)
print(result.name)
>>> 'foo'

Advanced Usage

We can use pymarshaler to handle containers as well. Again we take advantage of python's robust typing system

>> '{foo, bar}'">
from dataclasses import dataclass
from pymarshaler.marshal import Marshal
from typing import Set
import json

@dataclass
class TestContainer:
 
    container: Set[str]
    

marshal = Marshal()
container_instance = TestContainer({'foo', 'bar'})        
blob = marshal.marshal(container_instance)
print(blob.decode())
>>> '{container: ["foo", "bar"]}'

result = marshal.unmarshal(TestContainer,json.loads(blob))
print(result.container)
>>> '{foo, bar}'

Pymarshaler can also handle containers that store user defined types. The Set[str] could easily have been Set[UserDefinedType]

Pymarshaler also supports default values, and will use any default values supplied in the __init__ if those values aren't present in the JSON data.

from dataclasses import dataclass
from pymarshaler.marshal import Marshal

@dataclass
class TestWithDefault:
    
    name: str = 'foo'


marshal = Marshal()
result = marshal.unmarshal(TestWithDefault, {})
print(result.name)
>>> 'foo'

Pymarshaler will raise an error if any non-default attributes aren't given

Pymarshaler also supports a validate method on creation of the python object. This method will be called before being returned to the user.

from dataclasses import dataclass
from pymarshaler.marshal import Marshal


@dataclass
class TestWithValidate:
    
    name: str

    def validate(self):
        print(f'My name is {self.name}!')


marshal = Marshal()
result = marshal.unmarshal(TestWithValidate, {'name': 'foo'})
>>> 'My name is foo!'

This can be used to validate the python object right at construction, potentially raising an error if any of the fields have invalid values

It's also possible to register your own custom unmarshaler for specific user defined classes.

from dataclasses import dataclass

from pymarshaler.arg_delegates import ArgBuilderDelegate 
from pymarshaler.marshal import Marshal


@dataclass
class ClassWithMessage:
    
    message: str        


class ClassWithCustomDelegate:

    def __init__(self, message_obj: ClassWithMessage):
        self.message_obj = message_obj


class CustomDelegate(ArgBuilderDelegate):

    def __init__(self, cls):
        super().__init__(cls)

    def resolve(self, data):
        return ClassWithCustomDelegate(ClassWithMessage(data['message']))


marshal = Marshal()
marshal.register_delegate(ClassWithCustomDelegate, CustomDelegate)
result = marshal.unmarshal(ClassWithCustomDelegate, {'message': 'Hello from the custom delegate!'})
print(result.message_obj)
>>> 'Hello from the custom delegate!'

The result from any delegate should be the initialized resulting class instance

You might also like...
cysimdjson - Very fast Python JSON parsing library

Fast JSON parsing library for Python, 7-12 times faster than standard Python JSON parser.

simplejson is a simple, fast, extensible JSON encoder/decoder for Python

simplejson simplejson is a simple, fast, complete, correct and extensible JSON http://json.org encoder and decoder for Python 3.3+ with legacy suppo

import json files directly in your python scripts
import json files directly in your python scripts

Install Install from git repository pip install git+https://github.com/zaghaghi/direct-json-import.git Use With the following json in a file named inf

Python script for converting .json to .md files using Mako templates.

Install Just install poetry and update script dependencies Usage Put your settings in settings.py and .json data (optionally, with attachments) in dat

json|dict to python object

Pyonize convert json|dict to python object Setup pip install pyonize Examples from pyonize import pyonize

Editor for json/standard python data
Editor for json/standard python data

Editor for json/standard python data

Convert your JSON data to a valid Python object to allow accessing keys with the member access operator(.)

JSONObjectMapper Allows you to transform JSON data into an object whose members can be queried using the member access operator. Unlike json.dumps in

Define your JSON schema as Python dataclasses

Define your JSON schema as Python dataclasses

A Python tool that parses JSON documents using JsonPath

A Python tool that parses JSON documents using JsonPath

Comments
  • [0.4.0] delegates are now functions to avoid creating a ton of classes

    [0.4.0] delegates are now functions to avoid creating a ton of classes

    Rather than using classes as delegates, we use functions. This means we aren't spawning classes for every single call to resolve. This is a performance boost, and reduces memory consumption, and garbage collection.

    This will change up how this package is used which I think is acceptable given that we are on version < 1

    opened by hgromer 1
  • Improve performance

    Improve performance

    Right now, we are performing an allocation for every delegate we create. We can make this more performant.

    One option is to use function pointers rather than classes to resolve data into its class form

    enhancement 
    opened by hgromer 0
Releases(0.4.0)
Owner
Hernan Romer
Software Engineer at HubSpot.
Hernan Romer
Same as json.dumps or json.loads, feapson support feapson.dumps and feapson.loads

Same as json.dumps or json.loads, feapson support feapson.dumps and feapson.loads

boris 5 Dec 01, 2021
Python script to extract news from RSS feeds and save it as json.

Python script to extract news from RSS feeds and save it as json.

Alex Trbznk 14 Dec 22, 2022
RedisJSON - a JSON data type for Redis

RedisJSON is a Redis module that implements ECMA-404 The JSON Data Interchange Standard as a native data type. It allows storing, updating and fetching JSON values from Redis keys (documents).

3.4k Dec 29, 2022
API that provides Wordle (ES) solutions in JSON format

Wordle (ES) solutions API that provides Wordle (ES) solutions in JSON format.

Álvaro García Jaén 2 Feb 10, 2022
Wikidot-forum-dump - Simple Python script that dumps a Wikidot wiki forum into JSON structures.

wikidot-forum-dump Script is partially based on 2stacks by bluesoul: https://github.com/scuttle/2stacks To dump a Wiki's forum, edit config.py and put

ZZYZX 1 Jun 29, 2022
MOSP is a platform for creating, editing and sharing validated JSON objects of any type.

MONARC Objects Sharing Platform Presentation MOSP is a platform for creating, editing and sharing validated JSON objects of any type. You can use any

CASES Luxembourg 72 Dec 14, 2022
import json files directly in your python scripts

Install Install from git repository pip install git+https://github.com/zaghaghi/direct-json-import.git Use With the following json in a file named inf

Hamed Zaghaghi 51 Dec 01, 2021
With the help of json txt you can use your txt file as a json file in a very simple way

json txt With the help of json txt you can use your txt file as a json file in a very simple way Dependencies re filemod pip install filemod Installat

Kshitij 1 Dec 14, 2022
A fast JSON parser/generator for C++ with both SAX/DOM style API

A fast JSON parser/generator for C++ with both SAX/DOM style API Tencent is pleased to support the open source community by making RapidJSON available

Tencent 12.6k Dec 30, 2022
Console to handle object storage using JSON serialization and deserealization.

Console to handle object storage using JSON serialization and deserealization. This is a team project to develop a Python3 console that emulates the AirBnb object management.

Ronald Alexander 3 Dec 03, 2022
The ldap2json script allows you to extract the whole LDAP content of a Windows domain into a JSON file.

ldap2json The ldap2json script allows you to extract the whole LDAP content of a Windows domain into a JSON file. Features Authenticate with password

Podalirius 68 Dec 07, 2022
cysimdjson - Very fast Python JSON parsing library

Fast JSON parsing library for Python, 7-12 times faster than standard Python JSON parser.

TeskaLabs 235 Dec 29, 2022
Define your JSON schema as Python dataclasses

Define your JSON schema as Python dataclasses

62 Sep 20, 2022
A daily updated JSON dataset of all the Open House London venues, events, and metadata

Open House London listings data All of it. Automatically scraped hourly with updates committed to git, autogenerated per-day CSV's, and autogenerated

Jonty Wareing 4 Jan 01, 2022
Ibmi-json-beautify - Beautify json string with python

Ibmi-json-beautify - Beautify json string with python

Jefferson Vaughn 3 Feb 02, 2022
json|dict to python object

Pyonize convert json|dict to python object Setup pip install pyonize Examples from pyonize import pyonize

bilal alpaslan 45 Nov 25, 2022
jq for Python programmers Process JSON and HTML on the command-line with familiar syntax.

jq for Python programmers Process JSON and HTML on the command-line with familiar syntax.

Denis Volk 3 Jan 09, 2022
Package to Encode/Decode some common file formats to json

ZnJSON Package to Encode/Decode some common file formats to json Available via pip install znjson In comparison to pickle this allows having readable

ZINC 2 Feb 02, 2022
A JSON utility library for Python featuring Django-style queries and mutations.

JSON Enhanced JSON Enhanced implements fast and pythonic queries and mutations for JSON objects. Installation You can install json-enhanced with pip:

Collisio Technologies 4 Aug 22, 2022
Editor for json/standard python data

Editor for json/standard python data

1 Dec 07, 2021