Remove new lines from JSON

Viewed 26356

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.

3 Answers

use JSON.stringify and remove the line break;

var json = JSON.stringify(jsonData);
json = json.replace(/\\n/g, '');
Related