Skip to content

Seamlessly encode and decode python objects to json while maintaining their types.

License

Notifications You must be signed in to change notification settings

maspe36/json_typer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

json_typer

Seamlessly encode and decode python objects to json while maintaining their types.

Installation

pip install json_typer

Usage

Making a class type serializable

To make a class type serializable (a.k.a to seamlessly serialize the class to JSON and then when loading the JSON convert the object to its old type) inherit from TypeSerializable and make sure you are passing *args, **kwargs to the super constructor.

from json_typer import TypeSerializable


class Foo(TypeSerializable):
    def __init__(bar, baz="", *args, **kwargs):
        self.bar = bar
        self.baz = baz

Exporting a type serializable class

from json_typer import io

foo = Foo(bar="example")

io.exportJSON(path=EXAMPLE_FILE, data=foo)

EXAMPLE_FILE contents

{
    "type": "Foo"
    "module": "Foo"
    "bar": "example",
    "baz": ""
}

Importing a JSON file

from json_typer import io


foo = io.loadJSON(path=EXAMPLE_FILE)

Access the loaded attributes like you normally would

foo.bar
>>> example

isinstance(foo, Foo)
>>> True

Running Tests

Open a terminal in this projects root directory and type python -m unittest

Limitations

  • Must have *args, **kwargs in the constructor and passed to the super call in any class that inherits from TypeSerializable
  • A class that inherits from TypeSerializable cannot implement _type or _module attributes

Authors

  • Sam Privett - Initial work - maspe36

License

This project is licensed under the MIT License - see the LICENSE.md file for details

About

Seamlessly encode and decode python objects to json while maintaining their types.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages