2012-11-03 123 views
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。有没有人看到类似的东西?

回答

6

Colander,加上limone完全是这样。

您定义使用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)) 
+0

'deserialized'似乎字典,所以我要'反序列化[ “如first_name”] '而不是'deserialized.first_name',这不完全是我所期待的。看起来像验证器比映射器更重要。 – agibalov

+0

是的,抱歉;漏勺仅对简单类型进行验证和反序列化。更新以添加缺失的部分:limone。 –

+0

使用limone是否“安全”? 它已经很久没有更新,并保持在“alpha”版本。 –