Skip to main content

Simple utilities to map JSON to and from Python Objects.

https://travis-ci.org/kevinbeaty/medea.png?branch=master

medea

medea is a singledispatch function for JSON encoding.

lists, tuples and sequences are converted to lists. Items and values of dicts are recursively dispatched. Other types should be registered with dispatch function.

medea.register(date, lambda obj: obj.strftime('%Y-%m-%d'))

dob = date(1974, 3, 1)
assert medea(dob) == '1974-03-01'

bob = {
    'name': 'Bob',
    'age': 38,
    'colors': ('blue', 'red'),
    'dob': dob}

assert medea(bob) == {
    'name': 'Bob',
    'age': 38,
    'colors': ['blue', 'red'],
    'dob': '1974-03-01'}

Custom objects can be registered with a mapper:

class Pet(object):
    pass


class Dog(Pet):
    def __init__(self, name):
        self.name = name
        self.kind = 'Dog'


class Cat(Pet):
    def __init__(self, name):
        self.name = name
        self.kind = 'Cat'


class PetPerson(Person):
    pass


medea.register(PetPerson, MedeaCamelMapper('first_name', 'last_name', 'pets'))
medea.register(Pet, MedeaCamelMapper('name', 'kind'))

anne = PetPerson('Anne', 'Frank')
fido = Dog('Fido')
spot = Dog('Spot')
garfield = Cat('Garfield')
anne.pets = [fido, spot, garfield]
assert medea(anne) == {
    'firstName': 'Anne',
    'lastName': 'Frank',
    'pets': [
        {'kind': 'Dog', 'name': 'Fido'},
        {'kind': 'Dog', 'name': 'Spot'},
        {'kind': 'Cat', 'name': 'Garfield'}]}

MedeaEncoder

MedeaEncoder is a JSONEncoder using the medea function.

MedeaMapper

Create a mapper using Python attribute names as arguments. Attributes that are not whitelisted will not be serialized:

class Person(object):
    def __init__(self, first_name, last_name,
                 address='', phone_number='', dob=''):
        self.first_name = first_name
        self.last_name = last_name
        self.address = address
        self.phone_number = phone_number
        self.dob = dob


bob = Person('Bob', 'Hope', '123 Main', '123', '1903-05-29')

mapper = MedeaMapper('first_name', 'last_name',
                     'address', 'phone_number', 'dob')

bob_json = {
    'first_name': 'Bob',
    'last_name': 'Hope',
    'address': '123 Main',
    'phone_number': '123',
    'dob': '1903-05-29'}

assert mapper.to_json(bob) == bob_json

Attribute names can be overridden using **kwargs.

bob = Person('Bob', 'Hope', '123 Main', '123', '1903-05-29')

mapper = MedeaMapper('address', 'dob',
                     first_name='firstName', last_name='lastName')

bob_json = {
    'firstName': 'Bob',
    'lastName': 'Hope',
    'address': '123 Main',
    'dob': '1903-05-29'}

assert mapper.to_json(bob) == bob_json

MedeaCamelMapper may be useful if JSON is camel cased.

bob = Person('Bob', 'Hope', '123 Main', '123', '1903-05-29')

mapper = MedeaCamelMapper('first_name', 'last_name',
                          'address', 'phone_number', 'dob')

bob_json = {
    'firstName': 'Bob',
    'lastName': 'Hope',
    'address': '123 Main',
    'phoneNumber': '123',
    'dob': '1903-05-29'}

assert mapper.to_json(bob) == bob_json

A mapper can also map attribues from JSON onto the object:

bob = Person('Bob', 'Hope', '123 Main', '123', '1903-05-29')

bob_json_full = {
    'firstName': 'Bob',
    'lastName': 'Hope',
    'address': '123 Main',
    'phoneNumber': '123',
    'DOB': '1903-05-29'}

fred_json = {
    'firstName': 'Fred',
    'lastName': 'Rodgers'}

mapper = MedeaCamelMapper('first_name', 'last_name')
mapper_full = MedeaCamelMapper('first_name', 'last_name',
                               'address', 'phone_number', dob='DOB')

assert mapper.to_json(bob) == bob_json
assert mapper_full.to_json(bob) == bob_json_full

# Override Bob's name from Fred
mapper.from_json(fred_json, bob)

# Mapper only serializes names
assert mapper.to_json(bob) == fred_json
assert mapper_full.to_json(bob) != bob_json_full
assert bob.first_name == 'Fred'
assert bob.last_name == 'Rodgers'
assert bob.address == '123 Main'
assert bob.phone_number == '123'
assert bob.dob == '1903-05-29'

# Revert back to Bob's name
mapper.from_json(bob_json, bob)
assert mapper.to_json(bob) == bob_json
assert mapper_full.to_json(bob) == bob_json_full

Metadata

Release files for Medea 0.3.2

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

Source distribution (sdist)

Source distribution for Medea 0.3.2
File Size Uploaded Provenance Actions
Medea-0.3.2.tar.gz 3.7 kB Without provenance Details for Medea-0.3.2.tar.gz

Release files / Medea-0.3.2.tar.gz

Download URL Medea-0.3.2.tar.gz
Size 3.7 kB
Tags Source
SHA-256 checksum
How to use checksums
920598a1d5eba0e82a5e2cc90ee5fc818153611eece98c6d8b3982ec068b2210
BLAKE2b-256 checksum
How to use checksums
2e13527c53b292a1775b8bb7df5eed863748d6a69a794787653524f027ac4c73
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for Medea 0.3.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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