Andrey Agibalov
Andrey Agibalov

Reputation: 7694

Typed JSON serialization/deserialization in Python

class Person:
    first_name = superjson.Property()
    last_name = superjson.Property()
    posts = superjson.Collection(Post)

class Post:
    title = superjson.Property()
    description = superjson.Property()

# ^^^ this approach is very similar to Django models/forms

Then, given JSON like this:

{
  "first_name": "John", 
  "last_name": "Smith",
  "posts": [
    {"title": "title #1", "description": "description #1"},
    {"title": "title #2", "description": "description #2"},
    {"title": "title #3", "description": "description #3"}
  ]
}

I want it to build a proper Person object with everything inside it set:

p = superjson.deserialize(json, Person) # note, root type is explicitly provided
print p.first_name # 'John'
print p.last_name # 'Smith'
print p.posts[0].title # 'title #1'
# etc...

So, I'm looking for this superjson. Did anyone see anything similar?

Upvotes: 1

Views: 3832

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121554

Colander, combined with limone does exactly this.

You define a schema using colander:

import colander
import limone


@limone.content_schema
class Characteristic(colander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    rating = colander.SchemaNode(colander.String())        


class Characteristics(colander.SequenceSchema):
    characteristic = Characteristic()


@limone.content_schema
class Person(colander.MappingSchema):
    id = colander.SchemaNode(colander.Int(),
                             validator=colander.Range(0, 9999))
    name = colander.SchemaNode(colander.String())
    phone = colander.SchemaNode(colander.String())
    characteristics = Characteristics()


class Data(colander.SequenceSchema):
    person = Person()

then pass in your JSON data structure:

deserialized = Data().deserialize(json.loads(json_string)) 

Upvotes: 6

Related Questions