如何在Python / Django中将字典列表转换为JSON? [英] How to convert a list of dictionaries to JSON in Python / Django?

查看:582
本文介绍了如何在Python / Django中将字典列表转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google上搜索并找到了答案,但这对我不起作用。我必须在Django中将列表作为 JsonResponse 发送,类似于:

I searched on Google and found an answer but it's not working for me. I have to send a list as JsonResponse in Django, similar to this:

list_to_json =[{"title": "hello there",
                "link": "www.domain.com",
                "date":   ...},
               {},{},{},...]

我正在通过应用StackOverflow将其转换为JSON < a href = https://stackoverflow.com/questions/11312733/python-convert-a-list-of-python-dictionaries-to-an-array-of-json-objects> question1 和<一个href = https://stackoverflow.com/questions/21525328/python-converting-a-list-of-dictionaries-to-json> question2 ,但这对我不起作用。我收到以下错误:

I am converting this to JSON by applying StackOverflow question1 and question2 but it's not working for me. I get the following error:

为了允许非字典对象被序列化,请将安全参数设置为False

这是我的代码:

    def json_response(request):
        list_to_json=[{"title": ..., "link": ..., "date": ...},{...}]
        return JsonResponse(json.dumps(list_to_json) )


推荐答案

return JsonResponse(list_to_json, safe=False)

看看文档


safe布尔值默认为True。如果设置为False,则可以传递任何对象进行序列化(否则仅允许使用dict实例)。如果安全是正确的,并且将非字典对象作为第一个参数传递,则将引发TypeError。

The safe boolean parameter defaults to True. If it’s set to False, any object can be passed for serialization (otherwise only dict instances are allowed). If safe is True and a non-dict object is passed as the first argument, a TypeError will be raised.

这篇关于如何在Python / Django中将字典列表转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆