Cyril
Cyril

Reputation: 109

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.

Upvotes: 9

Views: 37389

Answers (3)

hazan kazim
hazan kazim

Reputation: 958

use JSON.stringify and remove the line break;

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

Upvotes: 1

Muthu Kumaran
Muthu Kumaran

Reputation: 17930

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);

Upvotes: 16

Raymond Seger
Raymond Seger

Reputation: 1130

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

Upvotes: 0

Related Questions