知道这些问题很烦人,但我真的很困惑,所以非常感谢帮助。我正在尝试将字符串列表发送到前端并加载到 JavaScript 对象中。 Django 应用程序的相关部分:
在views.py中的处理函数中:
import json
def home(request):
test_list = ["(hello world\")"]
return render(request, 'app/home.html', {"test_list": json.dumps(test_list)})
在 home.html 中:
let parsed = JSON.parse('{{test_list|safe}}');
我收到错误:
Uncaught SyntaxError: Unexpected token ) in JSON at position 15
我尝试过的事情:
- running json.dumps directly on each (str) element of the list, not just on the whole list.
- Manually adding a backslash to each of (", ', (, ), [, ] )
- Manually adding two backslashes to each of (", ', (, ), [, ] )
- Not using |safe in the template
有效的方法只是删除每个 (", ', (, ), [, ] )。但我不能删除它们。我需要将它们转义。
以下是 Google Chrome 告诉我模板在失败的行处解析的内容:
let parsed = JSON.parse('["(hello world\")"]');
非常感谢您的帮助。
最佳答案
如果你定义
str = "(hello world\")";
然后JSON.parse(str);
会给出错误( Unexpected token ( in JSON at position 0
),因为没有以 (
开头的 JSON 对象(参见MDN: full JSON syntax)
为了在字符串中包含括号,您需要使用双引号创建一个包含括号的字符串(因为 JSON 只接受双引号)。
如果封闭的引号是双引号,则需要转义嵌套的双引号,请参阅下面的代码片段:
// using double quotes outside: need escaping for the inner double quotes to avoid confusion
str = "\"(hello world)\"";
console.log(JSON.parse(str));
// using single quotes outside: no need to escape
str = '"(hello world)"';
console.log(JSON.parse(str));
关于javascript - Python/Django 转义字符串列表,用于 Javascript 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56611826/