Easiest way to serialize a simple class object with simplejson?

前端 未结 7 2029
萌比男神i
萌比男神i 2020-12-07 15:55

I\'m trying to serialize a list of python objects with JSON (using simplejson) and am getting the error that the object \"is not JSON serializable\".

The class is a

7条回答
  •  无人及你
    2020-12-07 16:32

    I feel a bit silly about my possible 2 solutions rereading it now, of course when you use django-rest-framework, this framework have some excellent features buildin for this problem mentioned above.

    see this model view example on their website

    If you're not using django-rest-framework, this can help anyway:

    I found 2 helpfull solutions for this problem in this page: (I like the second one the most!)

    Possible solution 1 (or way to go): David Chambers Design made a nice solution

    I hope David does not mind I copy paste his solution code here:

    Define a serialization method on the instance's model:

    def toJSON(self):
    import simplejson
    return simplejson.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
    

    and he even extracted the method above, so it's more readable:

    def toJSON(self):
    fields = []
    for field in self._meta.fields:
        fields.append(field.name)
    
    d = {}
    for attr in fields:
        d[attr] = getattr(self, attr)
    
    import simplejson
    return simplejson.dumps(d)
    

    Please mind, it's not my solution, all the credits goes to the link included. Just thought this should be on stack overflow.

    This could be implemented in the answers above as well.

    Solution 2:

    My preferable solution is found on this page:

    http://www.traddicts.org/webdevelopment/flexible-and-simple-json-serialization-for-django/

    By the way, i saw the writer of this second and best solution: is on stackoverflow as well:

    Selaux

    I hope he sees this, and we can talk about starting to implement and improve his code in an open solution?

提交回复
热议问题