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

在React中如何将数组对象格式的字符串转换为可用数组?

解析失败原因

你调用JSON.parse()不生效是因为原始内容存在两个格式问题:

  1. 内容做了HTML实体转义,双引号被转成了"编码,不符合JSON格式要求
  2. 有效JSON数组外层额外包裹了一层冗余双引号,且字符串内部的换行符没有做JSON兼容转义

解决代码

// 你的原始输入字符串
const rawInput = `"[{\"insert\":\"Test\"},{\"insert\":\"
\",\"attributes\":{\"header\":1}},{\"insert\":\"Asdasfff\"},{\"insert\":\"
\",\"attributes\":{\"list\":\"bullet\"}},{\"insert\":\"Asadsf\"},{\"insert\":\"
\",\"attributes\":{\"list\":\"bullet\"}},{\"insert\":\"Sfsfsft\"},{\"insert\":\"
\",\"attributes\":{\"header\":2}},{\"insert\":\"Make\"},{\"insert\":\"
\",\"attributes\":{\"list\":\"unchecked\"}},{\"insert\":\"Back\"},{\"insert\":\"
\",\"attributes\":{\"list\":\"checked\"}},{\"insert\":\"Ban\"},{\"insert\":\"
\",\"attributes\":{\"list\":\"unchecked\"}},{\"insert\":\"Fg\"},{\"insert\":\"
\",\"attributes\":{\"list\":\"checked\"}}]"`;

// HTML实体解码工具方法
const decodeHtmlEntity = (str) => {
  const textarea = document.createElement('textarea');
  textarea.innerHTML = str;
  return textarea.value;
};

// 步骤1:解码HTML实体得到原始字符串
const decodedStr = decodeHtmlEntity(rawInput);
// 步骤2:去掉首尾冗余的外层双引号
const pureJsonStr = decodedStr.slice(1, -1);
// 步骤3:转义换行符避免JSON解析报错
const escapedStr = pureJsonStr.replace(/\n/g, '\\n');
// 步骤4:解析得到目标数组
const targetArray = JSON.parse(escapedStr);

// 打印验证结果
console.log(targetArray);

输出说明

解析得到的targetArray就是你需要的目标数组,结构完全匹配预期效果:

  • 每个元素保留原有的insert字段和attributes字段
  • 标题、无序列表、待办项的属性配置都完整保留

内容的提问来源于stack exchange,提问作者Anoop V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:54:03