如何在 Python/Django 中将字典列表转换为 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37909800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:06:28  来源:igfitidea点击:

How to convert a list of dictionaries to JSON in Python / Django?

pythonjsondjango

提问by shuboy2014

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

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

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

I am converting this to JSON by applying StackOverflow question1and question2but it's not working for me. I get the following error:

我通过应用 StackOverflow question1question2将其转换为 JSON,但它对我不起作用。我收到以下错误:

In order to allow non-dict objects to be serialized set the safe parameter to False

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

Here's my code:

这是我的代码:

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

回答by The Brewmaster

return JsonResponse(list_to_json, safe=False)

Take a look at the documentation:

看看文档

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.

?safe?boolean 参数默认为?True。如果设置为?False,则可以传递任何对象进行序列化(否则只允许?dict?instances)。如果?safe?is?True? 并且一个非dict?object 作为第一个参数传递,a?TypeError? 将被引发。

回答by Projesh Bhoumik

You have do include serializers or you can do this by using safe= False to your response data.
Like

您确实包含序列化程序,或者您可以通过对响应数据使用 safe= False 来做到这一点。
喜欢

return JsonResponse(list_to_json, safe=False)

回答by stackPusher

Adding this answer for anyone wondering why this isn't "safe" by default. Packing a non-dict data structure into a response makes the service vulnerable to a pre-ES5 JSON HiHymaning attack.

为任何想知道为什么默认情况下这不是“安全”的人添加此答案。将非 dict 数据结构打包到响应中会使服务容易受到 ES5 之前的 JSON 劫持攻击。

Basically, with the JSONResponse you're using here, if a user is authenticated to your site, he can now retrieve that list of {title, link, date} objects and that's fine. However, an attacker could include that endpoint as a script source on his own malicious page (cross site script inclusion, aka XSSI):

基本上,使用您在这里使用的 JSONResponse,如果用户通过了您网站的身份验证,他现在可以检索 {title, link, date} 对象的列表,这很好。但是,攻击者可以将该端点作为脚本源包含在他自己的恶意页面上(跨站点脚本包含,又名 XSSI):

<script src="https://www.yourwebsite.com/secretlinks/"></script>

Then, if an unsuspecting authenticated user navigates to the malicious page, the browser will unknowingly request the array of data from your site. Since your service is just returning an unassigned array, the attacker must also poison the js Array constructor (this is the part of the attack that was fixed in ES5). Before ES5, the attacker could simply override the Array constructor like so:

然后,如果毫无戒心的经过身份验证的用户导航到恶意页面,浏览器将在不知不觉中从您的站点请求数据数组。由于您的服务只是返回一个未分配的数组,攻击者还必须毒害 js 数组构造函数(这是在 ES5 中修复的攻击的一部分)。在 ES5 之前,攻击者可以简单地覆盖 Array 构造函数,如下所示:

Array = function() {secret = this;}

Now secretcontains your list of dictionaries, and is available to the rest of the attacker's script, where he can send it off to his own server. ES5 fixed this by forcing the use of brackets to be evaluated by the default Array constructor.

现在secret包含您的字典列表,并且可供攻击者脚本的其余部分使用,在那里他可以将其发送到他自己的服务器。ES5 通过强制使用括号由默认的 Array 构造函数计算来解决这个问题。

Why wasn't this ever an issue for dictionary objects? Simply because curly brackets in javascript denote an isolated scope, and so there's no way for the attacker to inject his own code into the scope created by the returned dictionary which is surrounded by curly brackets.

为什么这不是字典对象的问题?仅仅因为 javascript 中的大括号表示一个孤立的作用域,因此攻击者无法将自己的代码注入到由大括号包围的返回字典创建的作用域中。

More info here: https://security.stackexchange.com/questions/159609/how-is-it-possible-to-poison-javascript-array-constructor-and-how-does-ecmascrip?newreg=c70030debbca44248f54cec4cdf761bb

更多信息:https: //security.stackexchange.com/questions/159609/how-is-it-possible-to-poison-javascript-array-constructor-and-how-does-ecmascrip?newreg=c70030debbca44248f54cec4cdf761bb

回答by VHarisop

This is not a valid dictionary:

这不是有效的字典:

{"title": , "link" : , "date": }

because the values are missing. If you try adding the missing values instead, it works fine:

因为缺少值。如果您尝试添加缺失值,则效果很好:

>>> json.dumps([{"title": "hello there", "link": "www.domain.com", "date": 2016}, {}])
'[{"link": "www.domain.com", "date": 2016, "title": "hello there"}, {}]'