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
 |  Show 1 more comment

3 Answers 3

Reset to default 16

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

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