I'm developing some ajax application now, and I need use simplejson to serialize my data, but I found if the string in my data structure is not unicode encoded, simplejson just simple unicode it, but not use the default-encode to convert the string to unicode, so I write a simple function to convert the string in data structure to unicode, according the default-encode option in settings. Maybe it'll be some helpful to you.
from django.http import HttpResponse from django.utils import simplejson from django.conf import settings def json(data): encode = settings.DEFAULT_CHARSET return HttpResponse(simplejson.dumps(uni_str(data, encode))) def uni_str(a, encoding): if isinstance(a, (list, tuple)): s = [] for i, k in enumerate(a): s.append(uni_str(k, encoding)) return s elif isinstance(a, dict): s = {} for i, k in enumerate(a.items()): key, value = k s[uni_str(key, encoding)] = uni_str(value, encoding) return s elif isinstance(a, str) or (hasattr(a, '__str__') and callable(getattr(a, '__str__'))): if getattr(a, '__str__'): a = str(a) return unicode(a, encoding) elif isinstance(a, unicode): return a else: return a And this function can also deal with Translation object. Because for these objects, simple isinstance(a, str) will failed, so I also need to test them with: (hasattr(a, '__str__') and callable(getattr(a, '__str__')) So in the view code, you could do like this(assume above function is saved in ajax.py) import ajax def load(request): a = {'response':'ok', 'message':_('Thank you')} return ajax.json(a) That's is. -- I like python! My Blog: http://www.donews.net/limodou UliPad Site: http://wiki.woodpecker.org.cn/moin/UliPad UliPad Maillist: http://groups.google.com/group/ulipad --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~----------~----~----~----~------~----~------~--~---