[英]JSON.parse : Bad control character in string literal
I think this is a basic question, but I can't understand the reason.我认为这是一个基本问题,但我不明白原因。 in JSON, it's valid to has a special character like "asdfadf\tadfadf", but when try parse it, it's shown error.
在JSON中,“asdfadf\tadfadf”这样的特殊字符是合法的,但是当尝试解析它时,它显示错误。 eg.
例如。 code:
代码:
let s = '{"adf":"asdf\tasdfdaf"}';
JSON.parse(s);
Error:错误:
Uncaught SyntaxError: Bad control character in string literal in JSON at position 12
at JSON.parse (<anonymous>)
at <anonymous>:1:6
I need to understand what is the issue, and solution.我需要了解问题所在和解决方案。
You have to take into account that \t
will be involved in two parsing operations: first, when your string constant is parsed by JavaScript, and second, when you parse the JSON string with JSON.parse()
.您必须考虑到
\t
将涉及两个解析操作:首先,当您的字符串常量被 JavaScript 解析时,其次,当您使用JSON.parse()
解析 JSON 字符串时。 Thus you must use因此你必须使用
let s = '{"adf":"asdf\\tasdfdaf"}';
If you don't, you'll get the error you're seeing from the actual tab character embedded in the string.如果不这样做,您将看到从字符串中嵌入的实际制表符看到的错误。 JSON does not allow "control" characters to be embedded in strings.
JSON 不允许在字符串中嵌入“控制”字符。
Also, if the actual JSON content is being created in server-side code somehow, it's probably easier to skip building a string that you're immediately going to parse as JSON. Instead, have your code build a JavaScript object initializer directly:此外,如果实际的 JSON 内容是以某种方式在服务器端代码中创建的,则跳过构建您将立即解析为 JSON 的字符串可能更容易。相反,让您的代码直接构建 JavaScript object 初始化程序:
let s = { "adf": "asdf\tasdfdaf" };
In your server environment there is likely to be a JSON tool that will allow you to take a data structure from PHP or Java or whatever and transform that to JSON, which will also work as JavaScript syntax.在你的服务器环境中,可能有一个 JSON 工具,它允许你从 PHP 或 Java 或其他任何东西中获取数据结构,并将其转换为 JSON,这也将作为 JavaScript 语法工作。
let t = '{"adf":"asdf\\tasdfdaf"}';
var obj = JSON.parse(t) console.log(obj) var obj = JSON.parse(t) console.log(obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.