简体   繁体   English

从Django“安全”传递JSON到Javascript将添加JSON.parse方法无法解析的字符

[英]Passing JSON “safely” from Django to Javascript adds ' characters that can't be parse by the JSON.parse method

I am using the Django framework and I try to pass a list of JSON to my javascript. 我正在使用Django框架,并且尝试将JSON列表传递给我的JavaScript。

Here is how I proceeded: 这是我的处理方式:

On the server-side (Python/Django): 在服务器端(Python / Django):

context['my_json_list'] = [{'aaa': 'rst', 'bbb': 'uvw'}, {'ccc': 'xyz'}]
return context

On the client-side (html/javascript): 在客户端(html / javascript):

In the HTML: 在HTML中:

<script type="text/javascript">
  app.init("{{my_json_list|safe}}");

In the JS: 在JS中:

var app = (function ($) {
  return {
    init: function (my_json_list) {
      console.log(my_json_list);
      my_json_list = JSON.parse(my_json_list);
    }
  }
}

The console.log() prints out: console.log()输出:

[{&#39;aaa&#39;: &#39;rst&#39;, &#39;bbb&#39;: etc...

which does not seem "parsable" by JSON.parse since I get the following error: JSON.parse似乎“不可解析”,因为出现以下错误:

angular.js:11413 SyntaxError: Unexpected token & in JSON at position 2

Is it the proper way of doing what I want, if yes how to solve the parsing part on the JS-side? 是正确的做我想要的方法,如果是的话,如何解决JS端的解析部分? If no, what is the right way of doing what I want to achieve? 如果没有,做我想达到的目标的正确方法是什么?

JSON.parse(my_json_list);

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. JSON.parse()方法解析一个JSON字符串,以构造该字符串描述的JavaScript值或对象。

You didnt pass a string or valid Json so the method failed. 您没有传递字符串或有效的Json,因此方法失败。

Thats not valid json. 那不是有效的json。 You should check out jsonlint.com to make sure youre passing valid json. 您应该检查jsonlint.com,以确保您传递了有效的json。 The issue here is that its reading the single quote &#39; 这里的问题是它读取单引号&#39; is the code for '. 是'的代码。 You should use double quotes in your json. 您应该在json中使用双引号。

Example valid Json 有效的Json示例

{
    "my_list": [{
        "aaa": "rst",
        "bbb": "uvw"
    }, {
        "ccc": "xyz"
    }]
}

JSON JSON格式

Property names must be double-quoted strings; 属性名称必须为双引号字符串; trailing commas are forbidden. 禁止尾随逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM