Consider the following example.
请考虑以下示例。
<script>
var dirstruct=JSON.parse('{"Foo":{"Bar.txt":"\n"},"Blahblah.txt":"FooBar\n"}');
</script>
I have put the JSON inside the single quotes through the JSONLint, but when this file is loaded in Firefox, I get the following error.
我已经通过JSONLint将JSON放在单引号内,但是当在Firefox中加载此文件时,我收到以下错误。
SyntaxError: JSON.parse: bad control character in string literal at line 1 column 20 of the JSON data
What is the cause of this error and how can I correct it?
导致此错误的原因是什么?如何更正错误?
2 个解决方案
#1
1
The cause of the error is that "\n"
is interpreted as the literal newline character:
错误的原因是“\ n”被解释为文字换行符:
{"Foo":{"Bar.txt":"
"},"Blahblah.txt":"FooBar
"}
and this is an invalid JSON. You should esape \n
with backslash:
这是一个无效的JSON。你应该用反斜杠来说明:
var dirstruct=JSON.parse('{"Foo":{"Bar.txt":"\\n"},"Blahblah.txt":"FooBar\\n"}');
#2
1
Ruslan's answer highlighted the problem, but the solution he suggested was not the one I actually used, due to the fact that I was generating the \n
's from server-side code which didn't know the client had this problem.
Ruslan的回答强调了这个问题,但他建议的解决方案不是我实际使用的解决方案,因为我是从服务器端代码生成\ n的,而不知道客户端有这个问题。
The solution I actually used was String.raw
since that meant the server-side JSON generator could simply generate syntactically correct JSON without being concerned about it being re-interpreted by the Javascript String interpreter before being passed to the JSON parser.
我实际使用的解决方案是String.raw,因为这意味着服务器端JSON生成器可以简单地生成语法正确的JSON,而不用担心它被传递给JSON解析器之前由Javascript String解释器重新解释。
<script>
var dirstruct=JSON.parse(String.raw`{"Foo":{"Bar.txt":"\n"},"Blahblah.txt":"FooBar\n"}`);
</script>
Sometimes the MCVE can be too simple.
有时MCVE可能太简单了。
#1
1
The cause of the error is that "\n"
is interpreted as the literal newline character:
错误的原因是“\ n”被解释为文字换行符:
{"Foo":{"Bar.txt":"
"},"Blahblah.txt":"FooBar
"}
and this is an invalid JSON. You should esape \n
with backslash:
这是一个无效的JSON。你应该用反斜杠来说明:
var dirstruct=JSON.parse('{"Foo":{"Bar.txt":"\\n"},"Blahblah.txt":"FooBar\\n"}');
#2
1
Ruslan's answer highlighted the problem, but the solution he suggested was not the one I actually used, due to the fact that I was generating the \n
's from server-side code which didn't know the client had this problem.
Ruslan的回答强调了这个问题,但他建议的解决方案不是我实际使用的解决方案,因为我是从服务器端代码生成\ n的,而不知道客户端有这个问题。
The solution I actually used was String.raw
since that meant the server-side JSON generator could simply generate syntactically correct JSON without being concerned about it being re-interpreted by the Javascript String interpreter before being passed to the JSON parser.
我实际使用的解决方案是String.raw,因为这意味着服务器端JSON生成器可以简单地生成语法正确的JSON,而不用担心它被传递给JSON解析器之前由Javascript String解释器重新解释。
<script>
var dirstruct=JSON.parse(String.raw`{"Foo":{"Bar.txt":"\n"},"Blahblah.txt":"FooBar\n"}`);
</script>
Sometimes the MCVE can be too simple.
有时MCVE可能太简单了。