gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:16:42 27 4
gpt4 key购买 nike

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 或从 ISO-8601 中序列化/反序列化时间,或者通过几行代码轻松实现。

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

最佳答案

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)) 

关于python - Python 中的类型化 JSON 序列化/反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13209909/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com