'Remove new lines from JSON
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.
Solution 1:[1]
Strip \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);
Solution 2:[2]
use JSON.stringify
and remove the line break;
var json = JSON.stringify(jsonData);
json = json.replace(/\\n/g, '');
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Muthu Kumaran |
Solution 2 | hazan kazim |
Solution 3 | Raymond Seger |