简体   繁体   English

将对象数组转换为JSON

[英]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”)的示例。

I guess that JSON supports only POD formats and therefore you should use other methods of serialization for your complex objects. 我猜想JSON仅支持POD格式,因此您应该对复杂对象使用其他序列化方法。 Try pickle , but I'm not sure. 尝试泡菜 ,但我不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM