Skip to main content

jsoner

https://img.shields.io/travis/sschaffer92/jsoner.svg Documentation Status Coverage

Jsoner is a package aiming for making conversion to and from json easier.

Installation

Stable release

To install jsoner, run this command in your terminal:

$ pip install jsoner

This is the preferred method to install jsoner, as it will always install the most recent stable release.

From sources

The sources for jsoner can be downloaded from the Github repo.

You can either clone the public repository:

$ git clone git://github.com/sschaffer92/jsoner

Or download the tarball:

$ curl  -OL https://github.com/sschaffer92/jsoner/tarball/master

Once you have a copy of the source, you can install it with:

$ python setup.py install

Usage

Jsoner builds on the builtin json python package. Since you cannot serialize object to json by default it can be useful to have a nice way for doing so. This package provides three different ways to achieve this:

  • provide an to_dict and from_dict method:

from jsoner import dumps, loads
class A:
    def __init__(self, a):
        self.a = a

    def to_dict(self) -> dict:
        return {'a': self.a}

    @classmethod
    def from_dict(cls, data: dict) -> 'A':
        return A(**data)

a = A(42)
data = dumps(a)
a = loads(data)
  • or provide an to_str and from_str method:

from jsoner import dumps, loads
class A:
    def __init__(self, a):
        self.a = a

    def to_str(self) -> str:
        return str(self.a)

    @classmethod
    def from_str(cls, data: str) -> 'A':
        return A(data)

a = A('foo')
data = dumps(a)
a = loads(data)
  • or implement a conversion function pair (This way is especially useful if you don’t have direct access to the class definition):

from jsoner import dumps, loads
from jsoner import encoders, decoders
class A:
    def __init__(self, a):
        self.a = a

@encoders.register(A)
def encode_a(a: 'A') -> str:
    return a.a

@decoders.register(A)
def decode_a(data: str) -> str:
    return A(data)

a = A('foo')
data = dumps(a)
a = loads(data)

Jsoner can also deal with nested objects as long they are also serializable as described above.

Celery and Django

One good use case for the Jsoner package is the Celery serialization of tasks and task results.

To make Celery use Jsoner you can apply the following settings:

from celery import app
from kombu import serialization

from jsoner import dumps, loads

# register Jsoner
serialization.register('jsoner', dumps, loads, content_type='application/json')

app = Celery('Test')

# tell celery to use Jsoner
app.conf.update(
    accept_content=['jsoner'],
    task_serializer='jsoner',
    result_serializer='jsoner',
    result_backend='rpc'
)

# Celery can now serialize objects which can be serialized by Jsoner.
class A:
    def __init__(self, foo):
        self.foo = foo

    @classmethod
    def from_dict(cls, data: dict) -> 'A':
        return A(**data)

    def to_dict(self):
        return {'foo': self.foo}

a = A('bar')

@app.task
def task(obj: A) -> 'A':
    ...
    return obj

a = task.delay(a).get()

This way you can easily serialize django model instances and pass them to the Celery task.

 from django.db import models

 class Person(models.Model):
     first_name = models.CharField(max_length=30)
     last_name = models.CharField(max_length=30)

Then you can just pass the model to the celery task directly:

from django.db.models import Model
from jsoner import encoders, decoders

from .models import Person

# Create a conversion function pair which just saved the primary key.
@encoders.register(Model)
def to_primary_key(model: Model) -> int:
    return model.pk

# Load object from the primary key.
@decoders.register(Model)
def from_primary_key(pk: int, model_cls: Model) -> Model:
    return model_cls.objects.get(pk=pk)

p = Person(first_name="Foo", last_name="Bar")
p = task.delay(p).get()

Similar you could create a conversion function pair for querysets.

History

0.1.0 (2019-02-18)

  • First release on PyPI.

Metadata

Release files for jsoner 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for jsoner 0.2.0
File Size Uploaded
jsoner-0.2.0.tar.gz 26.1 kB Details

Release files / jsoner-0.2.0.tar.gz

Download URL jsoner-0.2.0.tar.gz
Size 26.1 kB
Tags Source
SHA-256 checksum
How to use checksums
d838411db82ff0bf5674e04852664762158b3a4c61144d318005e0fd3828f2ce
BLAKE2b-256 checksum
How to use checksums
8bf1b9154c7bb3fd86dc1c4de6484f378d25acdc0c05fcb0f3411bcbcc98eefe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

Release history Release notifications | RSS feed

This release

0.2.0 This release

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page