admin管理员组文章数量:1200985
Consider I have the following string:
{
"{\n <<<-- error
\"SomeKey\": {\n \"somevalue\": \"test\",\n,
\"AnotherKey\": \"Long string should be here \n another line break here \n and another line here \"
}
}
When you try to parse this string with JSON.parse, it throws an error that points to the first line break. Is there any way to get rid of the line breaks without removing \n that is not within quotation marks.
Consider I have the following string:
{
"{\n <<<-- error
\"SomeKey\": {\n \"somevalue\": \"test\",\n,
\"AnotherKey\": \"Long string should be here \n another line break here \n and another line here \"
}
}
When you try to parse this string with JSON.parse, it throws an error that points to the first line break. Is there any way to get rid of the line breaks without removing \n that is not within quotation marks.
Share Improve this question edited Apr 19, 2022 at 8:13 serenesat 4,70910 gold badges39 silver badges53 bronze badges asked Jul 20, 2017 at 7:33 CyrilCyril 1091 gold badge1 silver badge4 bronze badges 6- 3 What generates this json string? That's the point you should address, not trying to fix broken json later on. – Danmoreng Commented Jul 20, 2017 at 7:34
- So basically it returns a formatted JSON response, that contains \n in the beginning of every line. – Cyril Commented Jul 20, 2017 at 7:40
- share you actual JSON. – Muthu Kumaran Commented Jul 20, 2017 at 7:41
- What is that endpoint? It's not generating proper json. – Danmoreng Commented Jul 20, 2017 at 7:51
- How do you parse the XML then? – Danmoreng Commented Jul 20, 2017 at 9:14
3 Answers
Reset to default 16Strip \n
from the JSON string and do JSON.parse
var json_data = "{\n \"Fullname\": \"Alex Johnson\",\n \"FirstName\": \"Alex\", \n \"LastName\": \"Johnson\"\n }";
var obj = JSON.parse(json_data.replace(/\r?\n|\r/g, ''));
console.log(obj);
use JSON.stringify
and remove the line break;
var json = JSON.stringify(jsonData);
json = json.replace(/\\n/g, '');
You should use an array or a map and turn it into proper JSON string because that JSON string looks like it's made by faulty string concanetation logic
本文标签: javascriptRemove new lines from JSONStack Overflow
版权声明:本文标题:javascript - Remove new lines from JSON - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738606771a2102393.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论