Python中的类型化JSON序列化/反序列化

2024-10-01 11:40:18 发布

您现在位置: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

然后,假设JSON是这样的:

^{pr2}$

我想让它建立一个适当的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。有人见过类似的东西吗?在


Tags: name序列化titleispropertydescriptionpostclass
1条回答
网友
1楼 · 发布于 2024-10-01 11:40:18

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数据结构:

^{pr2}$

相关问题 更多 >