Usage

Warning

Take care for your data to be without cycles. Feeding the encoder cycles will probably dump your interpreter’s core.

MiniJSON implements the same interface as json or yaml, namely:

Warning

Cycles are not automatically detected. They might make the application hang or cause an MemoryError.

minijson.loads(data)

Reconstruct given JSON from a given value

Parameters

data – MiniJSON value to reconstruct it from. Must be able to provide bytes representation.

Returns

return value

Raises

DecodingError – something was wrong with the stream

minijson.dumps(data, default: Optional[Callable])

Serialize given data to a MiniJSON representation.

Note that this will load the initial value of current default float encoding mode and remember it throughout the streaming process, so you can’t change it mid-value.

To do so, please use MiniJSONEncoder

Parameters
  • data – data to serialize

  • default – a function that should be used to convert non-JSONable objects to JSONable ones. Default, None, will raise an EncodingError upon encountering such a value

Returns

return MiniJSON representation

Raises

EncodingError – object not serializable

minijson.dump(data, cio: _io.BytesIO, default: Optional[Callable])

Write an object to a stream.

Note that this will load the initial value of current default float encoding mode and remember it throughout the streaming process, so you can’t change it mid-value.

To do so, please use MiniJSONEncoder

Parameters
  • data – object to write

  • cio – stream to write to

  • default – a callable/1 that should return a JSON-able representation for objects that can’t be JSONed otherwise

Returns

amount of bytes written

Raises

EncodingError – invalid data

minijson.parse(data, starting_position)

Parse given stream of data starting at a position and return a tuple of (how many bytes does this piece of data take, the piece of data itself)

Parameters
  • data – stream of bytes to examine. Must be able to provide it’s bytes value via __bytes__

  • starting_position – first position in the bytestring at which to look

Returns

a tuple of (how many bytes does this piece of data take, the piece of data itself)

Return type

tp.Tuple[int, tp.Any]

Raises

DecodingError – invalid stream

For serializing objects you got the following:

minijson.dumps_object(data, default: Optional[Callable])

Dump an object’s __dict__.

Note that subobject’s __dict__ will not be copied. Use default for that.

Note that this will load the initial value of current default float encoding mode and remember it throughout the streaming process, so you can’t change it mid-value.

To do so, please use MiniJSONEncoder

Parameters
  • data – object to dump

  • default – a function that should be used to convert non-JSONable objects to JSONable ones. Default, None, will raise an EncodingError upon encountering such a value

Returns

resulting bytes

Raises

EncodingError – encoding error

minijson.loads_object(data, obj_class)

Load a dict from a bytestream, unserialize it and use it as a kwargs to instantiate an object of given class.

Parameters
  • data – data to unserialized

  • obj_class – class to instantiate

Returns

instance of obj_class

Raises
  • DecodingError – decoding error

  • TypeError – invalid class has been passed (the argument’s don’t match)

And the following exceptions:

class minijson.MiniJSONError

Base class for MiniJSON errors.

Note that it inherits from ValueError.

class minijson.EncodingError

Error during encoding

class minijson.DecodingError

Error during decoding

Controlling float output

By default, floats are output as IEEE 754 single. To switch to double just call:

minijson.switch_default_double()

Set default encoding of floats to IEEE 754 double

or to go again into singles:

minijson.switch_default_float()

Set default encoding of floats to IEEE 754 single

Serializing objects

If you got an object, whose entire contents can be extracted from it’s __dict__, and which can be instantiated with a constructor providing this __dict__ as keyword arguments to the program, you can use functions below to serialize/unserialize them:

minijson.dumps_object(data, default: Optional[Callable])

Dump an object’s __dict__.

Note that subobject’s __dict__ will not be copied. Use default for that.

Note that this will load the initial value of current default float encoding mode and remember it throughout the streaming process, so you can’t change it mid-value.

To do so, please use MiniJSONEncoder

Parameters
  • data – object to dump

  • default – a function that should be used to convert non-JSONable objects to JSONable ones. Default, None, will raise an EncodingError upon encountering such a value

Returns

resulting bytes

Raises

EncodingError – encoding error

minijson.loads_object(data, obj_class)

Load a dict from a bytestream, unserialize it and use it as a kwargs to instantiate an object of given class.

Parameters
  • data – data to unserialized

  • obj_class – class to instantiate

Returns

instance of obj_class

Raises
  • DecodingError – decoding error

  • TypeError – invalid class has been passed (the argument’s don’t match)

Dumps returns objects of type bytes.

Example:

from minijson import loads_object, dumps_object

class Test:
    def __init__(self, a):
        self.a = a

a = Test(3)
b = dumps_object(a)
c = loads_object(b, Test)
assert a.a == c.a

MiniJSONEncoder

There’s also a class available for encoding. Use it like you would a normal Python JSONEncoder:

class minijson.MiniJSONEncoder

A base class for encoders.

It is advised to use this class over dump() and dumps() due to finer grained control over floats.

Parameters
  • default – a default function used

  • use_double – whether to use doubles instead of floats to represent floating point numbers

  • use_strict_order – if set to True, dictionaries will be encoded by first dumping them to items and sorting the resulting elements, essentially two same dicts will be encoded in the same way.

Variables

use_double – (bool) whether to use doubles instead of floats (used when should_double_be_used() is not overrided)

default(v)

Convert an object to a MiniJSON-able representation.

A MiniJSONable representation is a dict, tuple, list, float, int, None, a bool or a bytes.

Overload this to provide your default function in other way that giving the callable as a parameter.

Parameters

v – object to convert

Returns

a Mini-JSONable representation

dump(data, cio: _io.BytesIO)

Write an object to a stream

Parameters
  • data – object to write

  • cio – stream to write to

Returns

amount of bytes written

Raises

EncodingError – invalid data

encode(v) bytes

Encode a provided object

Parameters

v – object to encode

Returns

returned bytes

should_double_be_used(y: float) bool

A function that you are meant to overload that will decide on a per-case basis which representation should be used for given number.

Parameters

y – number to check

Returns

True if double should be used, else False

Warning

The exact binary content output by MiniJSONEncoder will depend on internal Python hash order. To have same dicts return the same representation, you must use the parameter use_strict_order in MiniJSONEncoder.

MiniJSONEncoder will then extract the items from the dictionary, and sort them before dumping them to binary output. By enabling this feature you guarantee that identical dicts, serialized by identical Pythons will have the exact same binary representation.

So take care when serializing that with large dicts, use_strict_order will construct a list of all it’s items, while serializing a normal dict won’t. Only then strict order will be guaranteed. Your keys must be comparable anyway.