【发布时间】:2017-01-20 14:34:32
【问题描述】:
我有一个要构建大量 JSON 对象的需求。并且有许多不同的定义,理想情况下我想像类一样管理它们并构造对象并按需将它们转储到 JSON。
是否有现成的包装/食谱让我可以执行以下操作
为了简单起见,假设我需要代表正在工作、学习或两者兼有的人:
[{
"Name": "Foo",
"JobInfo": {
"JobTitle": "Sr Manager",
"Salary": 4455
},
{
"Name": "Bar",
"CourseInfo": {
"CourseTitle": "Intro 101",
"Units": 3
}]
我想创建可以转储有效 JSON 的对象,但创建时像常规的 python 类。
我想像 db 模型一样定义我的类:
class Person:
Name = String()
JobInfo = Job()
CourseInfo = Course()
class Job:
JobTitle = String()
Salary = Integer()
class Course:
CourseTitle = String()
Units = Integer()
persons = [Person("Foo", Job("Sr Manager", 4455)), Person("Bar", Course("Intro 101", 3))]
person_list = list(persons)
print person_list.to_json() # this should print the JSON example from above
编辑
我编写了自己的迷你框架来完成此操作。它可以通过 pip 获得
pip install pymodjson
此处提供了代码和示例:(MIT) https://github.com/saravanareddy/pymodjson
【问题讨论】:
-
See here。对于验证部分,您需要编写自己的
JSONEncoder。