Django对象不是JSON可序列化的

时间:2014-12-28 09:33:52

标签: python json django serialization

我有以下用于序列化查询集的代码:

def get_shop_categories(request):
    if request.method == 'POST':
        parent_id = int(request.POST.get('parent_id'))

        categories = (ShopCategory.objects.filter(enabled=True, parent=parent_id).values('id', 'title'))
        json_posts = json.dumps(categories)

        return HttpResponse(
            json_posts,
            content_type="application/json"
        )

    else:
        return HttpResponse(
            json.dumps({"success": False}),
            content_type="application/json"
        ) 

我想要它返回的是:

[{'id': 2, 'title': 'Tennis'}, {'id': 4, 'title': 'Basket'}]

相反,我收到了这个错误:

TypeError at /ajax/get_shop_categories
[{'id': 2, 'title': 'Tennis'}, {'id': 4, 'title': 'Basket'}] is not JSON serializable

我也以这种方式使用序列化:

categories = ShopCategory.objects.filter(enabled=True, parent=parent_id)                       
#json_posts = json.dumps(categories)
#objectQuerySet = ConventionCard.objects.filter(ownerUser = user)
json_posts = serializers.serialize('json', list(categories), fields=('id', 'title')) 

但是我得到了什么,我不喜欢:

 [{"fields":{"title":"Tennis"},"pk":2,"model":"appname.shopcategory"},{"fields":{"title":"Basket"},"pk":4,"model":"appname.shopcategory"}]

1 个答案:

答案 0 :(得分:2)

categories = ShopCategory.objects.filter(enabled=True, parent=parent_id).values('id', 'title')
json_posts = mark_safe(json.dumps(list(categories), ensure_ascii=False))
相关问题