[英]Convert an array of objects to JSON
I am using web.py
to make a simple web service, to return an array of object
. 我正在使用
web.py
制作简单的Web服务,以返回array of object
。 I was constructing a JSON String
manually, now I want to replace it with a JSON Library
. 我当时是在手动构造
JSON String
,现在想用JSON Library
替换它。 I am trying to use JSON
for this purpose. 我正在尝试为此目的使用
JSON
。
This is how I am doing it: 这就是我的做法:
return json.dump(schedules.__dict__)
schedules
is a list of schedule
. schedules
是名单schedule
。 This is how a schedule
object looks like: schedule
对象的外观如下所示:
class Schedule:
def __init__(self):
self._matchDate = None
self._matchTime = None
@property
def matchDate(self):
return self._matchDate
@property
def matchTime(self):
return self._matchTime
@matchTime.setter
def matchTime(self, value):
self._matchTime = value
@matchDate.setter
def matchDate(self, value):
self._matchDate = value
This is the error which I get: 这是我得到的错误:
<type 'exceptions.AttributeError'> at /Schedule
'list' object has no attribute '__dict__'
Python /home/faizan/PycharmProjects/Soccer/Rest.py in GET, line 24
Web GET http://localhost:8080/Schedule
How do I go about serializing the objects in JSON? 我该如何序列化JSON中的对象?
I think the proper approach here is a custom JSONEncoder that knows how to handle all your special types. 我认为这里的正确方法是自定义JSONEncoder,它知道如何处理所有特殊类型。 Then you can do
json.dump(schedules, cls=MyJSONEncoder)
. 然后,您可以执行
json.dump(schedules, cls=MyJSONEncoder)
。 Here's an example for extending JSONEncoder (search for "Extending JSONEncoder"). 这是扩展JSONEncoder (搜索“扩展JSONEncoder”)的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.