59

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 django.core.serializers, but when I did, I got

AttributeError: 'str' object has no attribute '_meta' 

It seems this can be used only for Django objects. How can I serialize simple, Python objects?

1
  • 2
    Can you include a snippet of the actual code you actually used that produced this error? Commented Jan 27, 2010 at 14:45

3 Answers 3

106

You can use pure Python to do it:

import json list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4) json.dumps(list) # '[1, 2, [3, 4]]' 
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, it's a new module in 2.6, I don't have to use simplejson. Thanks a lot :-)
I simply cannot parse the dumped JSON file, because in this file, JSON_ARRAY is the direct child of another JSON_ARRAY.
How to get it back to list?
7

If using Python 2.5, you may need to import simplejson:

try: import json except ImportError: import simplejson as json 

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.