Skip to main content

For serializing Python objects to JSON and back

Project description

PyPI version Build Status Scrutinizer Code Quality Maintainability

jsons

A Python lib (Python3.5+) for serializing Python objects to dicts or strings and for deserializing dicts or strings to Python objects.

Installation

pip install jsons

Usage

import jsons


some_instance = jsons.load(some_dict, SomeClass)  # Deserialization
some_dict = jsons.dump(some_instance)  # Serialization

API overview

  • dump(obj: object) -> dict: serializes an object to a dict.
  • load(json_obj: dict, cls: type = None) -> object: deserializes a dict to an object of type cls.
  • dumps(obj: object, *args, **kwargs) -> str: serializes an object to a string.
  • loads(s: str, cls: type = None, *args, **kwargs) -> object deserializes a string to an object of type cls.
  • set_serializer(c: callable, cls: type) -> None: sets a custom serialization function for type cls.
  • set_deserializer(c: callable, cls: type) -> None: sets a custom deserialization function for type cls.

Example with dataclasses

from dataclasses import dataclass
from typing import List
import jsons


# You can use dataclasses (since Python3.7). Regular Python classes (Python3.5+) will work as well as long as 
# type hints are present for custom classes.
@dataclass
class Student:
    name: str


@dataclass
class ClassRoom:
    students: List[Student]


c = ClassRoom([Student('John'), Student('Mary'), Student('Greg'), Student('Susan')])
dumped_c = jsons.dump(c)
print(dumped_c)
# Prints:
# {'students': [{'name': 'John'}, {'name': 'Mary'}, {'name': 'Greg'}, {'name': 'Susan'}]}
loaded_c = jsons.load(dumped_c, ClassRoom)
print(loaded_c)
# Prints:
# ClassRoom(students=[Student(name='John'), Student(name='Mary'), Student(name='Greg'), Student(name='Susan')])

Example with regular classes

from typing import List
import jsons


class Student:
    # Since ``name`` is expected to be a string, no type hint is required.
    def __init__(self, name):
        self.name = name


class ClassRoom:
    # Since ``Student`` is a custom class, a type hint must be given.
    def __init__(self, students: List[Student]):
        self.students = students


c = ClassRoom([Student('John'), Student('Mary'), Student('Greg'), Student('Susan')])
dumped_c = jsons.dump(c)
print(dumped_c)
# Prints:
# {'students': [{'name': 'John'}, {'name': 'Mary'}, {'name': 'Greg'}, {'name': 'Susan'}]}
loaded_c = jsons.load(dumped_c, ClassRoom)
print(loaded_c)
# Prints:
# <__main__.ClassRoom object at 0x0337F9B0>

Advanced features

Overriding the default (de)serialization behavior

You may alter the behavior of the serialization and deserialization processes yourself by defining your own custom serialization/deserialization functions.

jsons.set_serializer(custom_serializer, datetime)  # A custom datetime serializer.
jsons.set_deserializer(custom_deserializer, str)  # A custom string deserializer.

Transforming the JSON keys

You can have the keys transformed by the serialization or deserialization process by providing a transformer function that takes a string and returns a string.

result = jsons.dump(some_obj, jsons.KEY_TRANSFORMER_CAMELCASE)
# result could be something like: {'thisIsTransformed': 123}

result = jsons.load(some_dict, SomeClass, jsons.KEY_TRANSFORMER_SNAKECASE)
# result could be something like: {'this_is_transformed': 123}

The following casing styles are supported:

KEY_TRANSFORMER_SNAKECASE   # snake_case
KEY_TRANSFORMER_CAMELCASE   # camelCase
KEY_TRANSFORMER_PASCALCASE  # PascalCase
KEY_TRANSFORMER_LISPCASE    # lisp-case

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

jsons-0.2.2.tar.gz (7.8 kB view details)

Uploaded Source

Built Distribution

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

jsons-0.2.2-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file jsons-0.2.2.tar.gz.

File metadata

  • Download URL: jsons-0.2.2.tar.gz
  • Upload date:
  • Size: 7.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for jsons-0.2.2.tar.gz
Algorithm Hash digest
SHA256 f84d164d4d796dbfe05ddc8ff9c8f9698c074aba5ea7f1abd6b45a6810fadcc9
MD5 6b33e8bc952754bd81bbfce78d77dbea
BLAKE2b-256 288f58d8ded3e0c8563fecff34db085dc39094fc102a3b94e4386a6ade8617ed

See more details on using hashes here.

File details

Details for the file jsons-0.2.2-py3-none-any.whl.

File metadata

File hashes

Hashes for jsons-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 5ae3793adf36a7b9b90a004b7fd15249fd9255afb810bb98e978ec8aa5beba31
MD5 0c6126e63fadd000cf9bb30880e1910f
BLAKE2b-256 9bc7bd507d32acf0d756fdb4e5f6320168fc1f27935e0f3d886990063653aa02

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