You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JavaScript中用RegEx将JSON转换为忽略空白的块数组咨询

JavaScript实现JSON转结构化字符数组的方案

核心正则表达式

匹配规则完全覆盖要求的所有有效元素,自动忽略空白:

/"(?:\\.|[^"\\])*"|[{}[\]:,]|null|true|false|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g

正则分段说明

  • " (?:\\.|[^"\\])* ":匹配双引号包裹的字符串,支持处理内部转义字符(比如\"、\\等场景不会断匹配)
  • [{}[\]:,]:匹配JSON结构所需的括号、冒号、逗号符号
  • null|true|false:匹配JSON原生字面量
  • -?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?:匹配整数、浮点数、科学计数法格式的数字

完整实现代码

function jsonToArray(jsonStr) {
  const reg = /"(?:\\.|[^"\\])*"|[{}[\]:,]|null|true|false|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g;
  const matches = jsonStr.match(reg) || [];
  return matches.map(item => {
    // 处理双引号包裹的字符串
    if (item.startsWith('"') && item.endsWith('"')) {
      // 解析JSON转义得到正常字符串
      return JSON.parse(item);
    }
    // 处理null
    if (item === 'null') return null;
    // 处理布尔值
    if (item === 'true') return true;
    if (item === 'false') return false;
    // 处理数字
    if (!isNaN(Number(item))) return Number(item);
    return item;
  });
}

测试示例

输入提供的示例JSON:

const input = ` { 
   "hello":"world",
   "\\"foo\\":"bar",
   "my_object":{
     "my_array": [
        1,
        null,
        { "my_key":"my_value" }
     ]
   }
 }`;

console.log(jsonToArray(input));

输出结果和期望完全一致:

[
  '{', 'hello', ':', 'world', ',', '"foo"', ':', 'bar', ',', 'my_object', ':', '{', 'my_array', ':', '[', 1, ',', null, ',', '{', 'my_key', ':', 'my_value', '}', ']', '}', '}'
]

内容的提问来源于stack exchange,提问作者Ron I

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:27:02