为什么我会收到这个 simplejson 异常?
Django 会给我这个异常
[(7, u'Acura'), (18, u'Alfa Romeo'), ...] is not JSON serializable
为什么当我尝试时
data = VehicleMake.objects.filter(model__start_year__gte=request.GET.get('year',0)).values_list('id','name')
return HttpResponse(simplejson.dumps(data, ensure_ascii=False), mimetype='application/json')
?
它只是一个简单的元组列表。它与我的其他硬编码列表一起使用,格式几乎完全相同。是因为字符串是unicode吗?我该如何处理?
当我将其编码为字典时,它工作正常:
def get_makes(request):
year = request.GET.get('year',0)
data = VehicleMake.objects.filter(model__start_year__lte=year, model__stop_year__gte=year).order_by('name').distinct().values_list('id','name')
return HttpResponse(simplejson.dumps(odict(data), ensure_ascii=False), mimetype='application/json')
有些品牌有重音字符......可能是这样吗?是的,这个列表很大(总共约 900 个)。
Why does Django give me this exception
[(7, u'Acura'), (18, u'Alfa Romeo'), ...] is not JSON serializable
When I try
data = VehicleMake.objects.filter(model__start_year__gte=request.GET.get('year',0)).values_list('id','name')
return HttpResponse(simplejson.dumps(data, ensure_ascii=False), mimetype='application/json')
?
It's just a simple list of tuples. It works with my other hard-coded list that's in almost exactly the same format. Is it because the strings are unicode? How do I handle that?
It works fine when I encode it as a dict:
def get_makes(request):
year = request.GET.get('year',0)
data = VehicleMake.objects.filter(model__start_year__lte=year, model__stop_year__gte=year).order_by('name').distinct().values_list('id','name')
return HttpResponse(simplejson.dumps(odict(data), ensure_ascii=False), mimetype='application/json')
Some makes have accented characters... could that be it? Yes, the list is big (~900 makes total).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这似乎工作正常:
所以它不是前几个元组。您需要深入挖掘记录列表以缩小问题范围。如果它很大,也许可以获取数据列表的一些片段并尝试对它们进行编码,以查看错误是否发生在任何特定片段中。
更新:好的,这可能是因为您的
data
对象是一个 QuerySet 而 simplejson 无法处理它。尝试使用 django 的 serialize 代替。 (或者将数据强制到列表中。)This seems to work fine:
So it's not the first couple of tuples. You'll need to dig deeper in the records list to narrow down the issue. If it's large, perhaps take some slices of the data list and try encoding those, to see if the error occurs in any particular segment.
UPDATE: OK, it's probably because your
data
object is a QuerySet and simplejson doesn't handle that. Try using django's serialize instead. (Or coerce the data to a list.)Ticket #6234 声称省略
ensure_ascii=False
将解决问题(但我不确定问题是否真正被理解):Ticket #6234 claims that leaving out
ensure_ascii=False
will resolve the problem (but I am not sure if the problem is really understood):而不是
使用
list(data)
并修改您的 Javascript 来使用它。Instead of
Use
list(data)
and modify your Javascript to work with it.