繁体   English   中英

JSON 中字符串文字中的错误控制字符位于位置 197 错误

[英]Bad control character in string literal in JSON at position 197 error

Bad control character in string literal in JSON at position 197 错误是我在尝试解析此 json 字符串时得到的:

var obj = JSON.parse('[{"name":"Charles freed from Nepal jail","content":"A French serial killer known as The Serpent, convicted of several tourist murders in Asia in the 1970s, has been released from a Nepalese prison.\r\n\r\nCharles Sobhraj, 78, was freed after a court ruled in favour of his age and good behaviour.\r\n\r\nHe spent 19 years in jail in Nepal for killing two North Americans in 1975.","id":"1"}]');

我真的不知道我做错了什么。

我肯定知道,如果我尝试在没有换行符的情况下解析 json,它就可以正常工作,但是当我尝试使用换行符来解析内容时,它就不起作用了。 我不确定这里有什么问题。

问题是你必须用另一个斜线转义你的换行符,如果你为你工作,你可以赞成这个答案,例如 \r\n

var obj = JSON.parse('[{"name":"Charles freed from Nepal jail","content":"A French serial killer known as The Serpent, convicted of several tourist murders in Asia in the 1970s, has been released from a Nepalese prison.\\r\\n\\r\\nCharles Sobhraj, 78, was freed after a court ruled in favour of his age and good behaviour.\\r\\n\\r\\nHe spent 19 years in jail in Nepal for killing two North Americans in 1975.","id":"1"}]')

你只需要写双\\

   var obj = JSON.parse(`[{"name":"Charles freed from Nepal jail","content":"A French serial killer known as The Serpent, convicted of several tourist murders in Asia in the 1970s, has been released from a Nepalese prison.\\r\\n\\r\\nCharles Sobhraj, 78, was freed after a court ruled in favour of his age and good behaviour.\\r\\n\\r\\nHe spent 19 years in jail in Nepal for killing two North Americans in 1975.","id":"1"}]`);

错误消息“字符串文字中的错误控制字符”通常表示您尝试将其解析为 JSON 的字符串中存在无效字符。

在这种情况下,问题似乎是由数组中第一个对象的“content”属性中存在“\r”(回车)和“\n”(换行)字符引起的。 这些字符在 JSON 字符串中是不允许的,必须删除或转义才能成功解析字符串。

要修复此错误,您可以使用 String.replace() 方法从“content”属性中删除“\r”和“\n”字符:

var obj = JSON.parse('[{"name":"Charles freed from Nepal jail","content":"A French serial killer known as The Serpent, convicted of several tourist murders in Asia in the 1970s, has been released from a Nepalese prison. Charles Sobhraj, 78, was freed after a court ruled in favour of his age and good behaviour. He spent 19 years in jail in Nepal for killing two North Americans in 1975.","id":"1"}]'.replace(/[\r\n]/g, ''));

或者,您可以通过在它们之前添加反斜杠来转义 '\r' 和 '\n' 字符:

var obj = JSON.parse('[{"name":"Charles freed from Nepal jail","content":"A French serial killer known as The Serpent, convicted of several tourist murders in Asia in the 1970s, has been released from a Nepalese prison.\\r\\n\\r\\nCharles Sobhraj, 78, was freed after a court ruled in favour of his age and good behaviour.\\r\\n\\r\\nHe spent 19 years in jail in Nepal for killing two North Americans in 1975.","id":"1"}]');
Either of these approaches should allow you to parse the JSON string successfully.

暂无
暂无

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

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