"Cost to Implement \nRate 5 to 1\nHigh = 5\nLow = 1"
as part of a JSON parses fine in jsonlint, but fails in Chrome with any of these approaches (each tried separately):
作为JSON的一部分在jsonlint中解析很好,但在Chrome中使用任何这些方法都失败了(每个方法都单独尝试):
sections = $.parseJSON(myJSONstr);
sections = JSON.parse(myJSONstr);
sections = eval('(' + myJSONstr + ')');
When I remove the "=" signs from the string in the JSON, all is fine. My users will need the ability to enter the = sign in the text they enter. Is there a way around this?
当我从JSON中的字符串中删除“=”符号时,一切都很好。我的用户需要能够在输入的文本中输入=符号。有没有解决的办法?
1 个解决方案
#1
6
It looks like you are entering the newline without escaping it. You need to escape the backslashes.
看起来你正在进入换行而不逃避它。你需要逃避反斜杠。
The following fails because you're entering a raw newline into the JSON, they must be escaped
以下操作失败是因为您要在JSON中输入原始换行符,必须对其进行转义
var obj = JSON.parse('{"prop": "Cost to Implement \nRate 5 to 1\nHigh = 5\nLow = 1"}');
Escape the backslashes
逃避反斜杠
// Works fine
var obj = JSON.parse('{"prop": "Cost to Implement \\nRate 5 to 1\\nHigh = 5\\nLow = 1"}');
Note that these new lines (and other characters that must escaped like tabs, backspaces...) will be automatically escaped if you correctly serialize your JSON objects. For example
请注意,如果您正确序列化JSON对象,这些新行(以及必须转义的其他字符,如制表符,退格键......)将自动转义。例如
// Correctly parses the new line
JSON.parse(JSON.stringify({prop: "Line1\nLine2\tAfterTab"}))
#1
6
It looks like you are entering the newline without escaping it. You need to escape the backslashes.
看起来你正在进入换行而不逃避它。你需要逃避反斜杠。
The following fails because you're entering a raw newline into the JSON, they must be escaped
以下操作失败是因为您要在JSON中输入原始换行符,必须对其进行转义
var obj = JSON.parse('{"prop": "Cost to Implement \nRate 5 to 1\nHigh = 5\nLow = 1"}');
Escape the backslashes
逃避反斜杠
// Works fine
var obj = JSON.parse('{"prop": "Cost to Implement \\nRate 5 to 1\\nHigh = 5\\nLow = 1"}');
Note that these new lines (and other characters that must escaped like tabs, backspaces...) will be automatically escaped if you correctly serialize your JSON objects. For example
请注意,如果您正确序列化JSON对象,这些新行(以及必须转义的其他字符,如制表符,退格键......)将自动转义。例如
// Correctly parses the new line
JSON.parse(JSON.stringify({prop: "Line1\nLine2\tAfterTab"}))