javascript - 从 JSON 中删除新行

标签 javascript json regex

考虑我有以下字符串:

{
  "{\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 的情况下消除换行符。

最佳答案

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

关于javascript - 从 JSON 中删除新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45208252/

相关文章:

java - JAX-RS 响应对象将对象字段显示为 NULL 值

php - 仅返回空格前的数字

javascript - 检查map中是否存在key

javascript - Extjs 4.0 中将组合框与一个商店链接起来

Javascript 将 html 格式的 <p> 标签复制到剪贴板

json - postgresql jsonb 包含 key :value on second level

json - 从 MS Access 解析 VBA 中的 JSON (US BLS),更新

Java replaceAll 与反向引用

javascript - js正则表达式在匹配后获取字符

javascript - 如何从 Marionette.js ItemView 模板访问 Backbone.Model 方法?