【问题标题】:Need help in formatting JSON (in JavaScript) with Stringify and Regex replace在使用 Stringify 和 Regex 替换格式化 JSON(在 JavaScript 中)方面需要帮助
【发布时间】:2021-04-23 06:27:54
【问题描述】:

我在正则表达式中遗漏了一些东西,它正在删除逗号前每个项目的最后一个字母。

示例代码:

let test_json = { 
    "a" : { "a1" : "one", "is_active" : true, "a2" : "two" },
    "b" : { "b1" : "one", "is_active" : true, "b2" : "two" } 
}; 

JSON.stringify(test_json, null, 3).replace(/[^}],\n( )*"/g, ',   "');

结果是:

"{
   "a": {
      "a1": "one,   "is_active": tru,   "a2": "two"
   },
   "b": {
      "b1": "one,   "is_active": tru,   "b2": "two"
   }
}"

我想要得到的是:

"{
   "a": {
      "a1": "one",   "is_active": true,   "a2": "two"
   },
   "b": {
      "b1": "one",   "is_active": true,   "b2": "two"
   }
}"

错误的地方:
"一,应该是"一",
"tru,应该是"true",

【问题讨论】:

  • "在非捕获组内匹配的文本仍然被消耗,与在任何组外匹配的文本相同。捕获组就像具有额外功能的非捕获组:除了分组,它允许您独立于整体匹配提取它匹配的任何内容。” - 来自:stackoverflow.com/questions/7505762/…

标签: javascript json regex


【解决方案1】:
JSON.stringify(test_json,null,3).replace(/([^}]?),\n( )*"/g, '$1,   "');

不确定这是最好的方法,但这是我想到的第一件事

【讨论】:

  • 谢谢,但这对我不起作用,因为它弄乱了“b”的格式,应该换行
【解决方案2】:

您的问题是您正在查找以下字符序列

  • 任何不是右大括号的字符
  • 逗号
  • 换行符
  • 任意数量的空格

并替换整个序列。由于 "true" 末尾的 "e" 不是右大括号,因此它也会被替换。

您需要的是序列中的第一项是“紧跟在右大括号之后的逗号”。您可以使用negative lookbehind 来执行此操作。

let test_json = {
  a: {
    a1: "one",
    is_active: true,
    a2: "two"
  },
  b: {
    b1: "one",
    is_active: true,
    b2: "two"
  },
};

const result = JSON.stringify(test_json, null, 3).replace(
  /(?<!}),\n\s*/g,
  ", "
);

console.log(result);

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多