在Python中输入JSON序列化/反序列化 [英] Typed JSON serialization/deserialization in Python

查看:122
本文介绍了在Python中输入JSON序列化/反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

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

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

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

  • 当然也应该促进序列化
  • 默认情况下,它应该与ISO-8601之间的时间进行序列化/反序列化,或者很容易用几行代码来实现.

    • Sure it should also facilitate serialization
    • It should either serialize/deserialize time to/from ISO-8601 by default or be easy to achieve this in couple lines of code.
    • 所以,我正在寻找这个superjson.有人看到过类似的东西吗?

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

      推荐答案

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

      then pass in your JSON data structure:

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

      这篇关于在Python中输入JSON序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆