Serializing list to JSON

后端 未结 3 1851
忘了有多久
忘了有多久 2020-12-02 18:31

I am sending information between client and Django server, and I would like to use JSON to this. I am sending simple information - list of strings. I tried using djang

3条回答
  •  醉话见心
    2020-12-02 19:06

    Yes, but then what do you do about the django objects? simple json tends to choke on them.

    If the objects are individual model objects (not querysets, e.g.), I have occasionally stored the model object type and the pk, like so:

    seralized_dict = simplejson.dumps(my_dict, 
                         default=lambda a: "[%s,%s]" % (str(type(a)), a.pk)
                         )
    

    to de-serialize, you can reconstruct the object referenced with model.objects.get(). This doesn't help if you are interested in the object details at the type the dict is stored, but it's effective if all you need to know is which object was involved.

提交回复
热议问题