从 JSON 中删除新行

新手上路,请多包涵

考虑我有以下字符串:

 {
  "{\n <<<-- error
     \"SomeKey\": {\n    \"somevalue\": \"test\",\n,
     \"AnotherKey\": \"Long string should be here \n another line break here \n and another line here \"
    }
}

当您尝试使用 JSON.parse 解析此字符串时,它会抛出指向第一个换行符的错误。有什么方法可以在不删除不在引号内的 \n 的情况下摆脱换行符。

原文由 Cyril 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 522
1 个回答

从 JSON 字符串中剥离 \n 并执行 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);

原文由 Muthu Kumaran 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题