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

如何将含JavaScript对象数组的字符串转为JavaScript对象数组?

解决方案

问题说明

你拿到的字符串是未包裹数组括号且属性名无引号的JavaScript对象字面量集合,不符合JSON规范,所以无法直接用JSON.parse()解析,下面提供几种可行的处理方式:

方式一:正则修正后转JSON

通过正则表达式补全数组结构、给属性名添加双引号、替换字符串单引号为双引号,转为标准JSON格式后解析:

// 假设你的原始字符串是这个
const rawStr = `{ name: 'Taco Salad', description: 'A dish made with lettuce, tomatoes, cheese, and seasoned ground beef or chicken, all served in a tortilla bowl.', nationality: 'Mexican', id: '1' },  { name: 'Fried Rice', description: 'A stir-fried rice dish with eggs, vegetables, and meat or seafood.', nationality: 'Chinese', id: '2' }, { name: 'Spaghetti Bolognese', description: 'An Italian dish of minced beef or pork in a tomato sauce, served with spaghetti.', nationality: 'Italian', id: '3' },`;

// 1. 去除末尾多余逗号,包裹成数组形式
const wrappedStr = `[${rawStr.trim().replace(/,$/, '')}]`;
// 2. 给属性名添加双引号,把字符串单引号替换为双引号
const jsonStr = wrappedStr.replace(/(\w+):/g, '"$1":').replace(/'/g, '"');
// 3. 解析为JavaScript数组
try {
  const dishArray = JSON.parse(jsonStr);
  console.log(dishArray);
} catch (err) {
  console.error('解析失败:', err);
}

方式二:使用eval(仅信任数据源可用)

如果能确保数据源绝对安全(比如内部API),可以直接用eval解析,因为这本身就是合法的JS对象语法:

const rawStr = `{ name: 'Taco Salad', description: 'A dish made with lettuce, tomatoes, cheese, and seasoned ground beef or chicken, all served in a tortilla bowl.', nationality: 'Mexican', id: '1' },  { name: 'Fried Rice', description: 'A stir-fried rice dish with eggs, vegetables, and meat or seafood.', nationality: 'Chinese', id: '2' }, { name: 'Spaghetti Bolognese', description: 'An Italian dish of minced beef or pork in a tomato sauce, served with spaghetti.', nationality: 'Italian', id: '3' },`;

try {
  // 去除末尾逗号后包裹成数组,用eval执行
  const dishArray = eval(`[${rawStr.trim().replace(/,$/, '')}]`);
  console.log(dishArray);
} catch (err) {
  console.error('解析失败:', err);
}

⚠️ 注意:eval会执行任意代码,若数据源不可信,可能导致安全风险,禁止在生产环境处理未知来源的字符串时使用。

方式三:手动修正格式(临时调试用)

如果字符串内容固定且简短,也可以手动给首尾加上[],给每个属性名加上双引号,把字符串的单引号换成双引号,直接写成数组:

const dishArray = [
  { "name": "Taco Salad", "description": "A dish made with lettuce, tomatoes, cheese, and seasoned ground beef or chicken, all served in a tortilla bowl.", "nationality": "Mexican", "id": "1" },
  { "name": "Fried Rice", "description": "A stir-fried rice dish with eggs, vegetables, and meat or seafood.", "nationality": "Chinese", "id": "2" },
  { "name": "Spaghetti Bolognese", "description": "An Italian dish of minced beef or pork in a tomato sauce, served with spaghetti.", "nationality": "Italian", "id": "3" }
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:55:18