[英]How can I resolve JSON parsing error 'JSON.parse: bad control character in string literal'?
[英]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.