Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 257
Cyril Avatar asked Jul 20 '17 07:07

Cyril


2 Answers

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);
like image 66
Muthu Kumaran Avatar answered Nov 15 '22 12:11

Muthu Kumaran


use JSON.stringify and remove the line break;

var json = JSON.stringify(jsonData);
json = json.replace(/\\n/g, '');
like image 20
hazan kazim Avatar answered Nov 15 '22 14:11

hazan kazim