从 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 许可协议

阅读 519
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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题