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
Generate code from JSON schema files

json-schema-codegen Generate code from JSON schema files. Table of contents Introduction Currently supported languages Requirements Installation Usage

Daniele Esposti 30 Dec 23, 2022
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

Alexey Borontov 6 Dec 07, 2021
Simple, minimal conversion of Bus Open Data Service SIRI-VM data to JSON

Simple, minimal conversion of Bus Open Data Service SIRI-VM data to JSON

Andy Middleton 0 Jan 22, 2022
Easy JSON wrapper modfied to wrok with suggestions

🈷️ Suggester Easy JSON wrapper modfied to wrok with suggestions. This was made for small discord bots, for big bots you should not use this. 📥 Usage

RGBCube 1 Jan 22, 2022
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
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
JsonParser - Parsing the Json file by provide the node name

Json Parser This project is based on Parsing the json and dumping it to CSV via

Ananta R. Pant 3 Aug 08, 2022
A Python application to transfer Zeek ASCII (not JSON) logs to Elastic/OpenSearch.

zeek2es.py This Python application translates Zeek's ASCII TSV logs into ElasticSearch's bulk load JSON format. For JSON logs, see Elastic's File Beat

Corelight, Inc. 28 Dec 22, 2022
JSONManipulator is a Python package to retrieve, add, delete, change and store objects in JSON files.

JSONManipulator JSONManipulator is a Python package to retrieve, add, delete, change and store objects in JSON files. Installation Use the package man

Andrew Polukhin 1 Jan 07, 2022
Simple Python Library to convert JSON to XML

json2xml Simple Python Library to convert JSON to XML

Vinit Kumar 79 Nov 11, 2022
Define your JSON schema as Python dataclasses

Define your JSON schema as Python dataclasses

62 Sep 20, 2022
A fast streaming JSON parser for Python that generates SAX-like events using yajl

json-streamer jsonstreamer provides a SAX-like push parser via the JSONStreamer class and a 'object' parser via the ObjectStreamer class which emits t

Kashif Razzaqui 196 Dec 15, 2022
JSONx - Easy JSON wrapper packed with features.

🈷️ JSONx Easy JSON wrapper packed with features. This was made for small discord bots, for big bots you should not use this JSON wrapper. 📥 Usage Cl

2 Dec 25, 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
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
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
A Cobalt Strike Scanner that retrieves detected Team Server beacons into a JSON object

melting-cobalt 👀 A tool to hunt/mine for Cobalt Strike beacons and "reduce" their beacon configuration for later indexing. Hunts can either be expans

Splunk GitHub 150 Nov 23, 2022
Low code JSON to extract data in one line

JSON Inline Low code JSON to extract data in one line ENG RU Installation pip install json-inline Usage Rules Modificator Description ?key:value Searc

Aleksandr Sokolov 12 Mar 09, 2022
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

Owen Trump 4 Jul 20, 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