JSON中字符串字面量中存在无效控制字符,位于197位置的错误。

5

当我尝试解析这个JSON字符串时,出现了“Bad control character in string literal in JSON at position 197”错误。

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,它可以正常工作,但是当我尝试使用带有换行符的内容时,它就无法工作。 我不确定问题出在哪里。


1
这个回答解决了你的问题吗?JSON中允许多行字符串吗? - phuzi
您需要对字符串值中的回车符“\r”进行编码/转义,因为当前的用法是不允许的。 - phuzi
1
这里到底发生了什么?为什么您在Javascript源代码中使用JSON字符串?它是否被服务器进程注入到代码中?如果是这样,解决方法是确保注入的JSON字符串在注入时正确转义,而不是尝试在消费JS中随后修复。 - spender
这段代码是多余的,输入一个 JSON 字符串仅仅为了生成一个 JavaScript 对象没有太多意义。直接将同样的输入作为原始对象输入并跳过 JSON.parse() 部分即可。如果这只是为了说明问题而进行的简化,那么它可能过于简化了,因为在许多语言中 \r\n 是转义序列。 - Álvaro González
2个回答

3

你只需要写两个反斜杠\\

   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"}]`);

1
问题在于您必须使用另一个斜杠转义换行符,例如 \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"}]')

我该如何使用PHP进行操作呢?因为我的JSON数据来自以下代码: header("Content-Type: application/json"); include "database_config/db_config.php"; $connection = mysqli_connect($db_config["server"], $db_config["login"], $db_config["password"], $db_config["database"]); $query = "SELECT * FROM articles"; $result = mysqli_query($connection, $query); $all_page = mysqli_fetch_all($result, MYSQLI_ASSOC); $to_js = json_encode($all_page); print($to_js); - Norbi
我能看一下你的MySQL数据库吗?我认为你获取结果的格式是错误的。 - Davy King
我真的以为...我回答得很正确。 - Davy King

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接