1
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

然后,给定这样的 JSON:

{
  "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"}
  ]
}

我希望它建立一个适当的Person对象,其中包含所有内容:

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...
  • 当然它也应该有助于序列化
  • 默认情况下,它应该序列化/反序列化与 ISO-8601 之间的时间,或者很容易在几行代码中实现这一点。

所以,我在找这个superjson。有没有人看到类似的东西?

4

1 回答 1

6

Colanderlimone结合起来就是这样做的。

您使用以下方式定义架构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()

然后传入你的 JSON 数据结构:

deserialized = Data().deserialize(json.loads(json_string)) 
于 2012-11-03T14:09:39.913 回答