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

如何在JavaScript中将"{width: '300'}"转为JSON对象?JSON.parse报错

解决方法

你遇到的问题是因为这个字符串不是标准JSON格式:标准JSON要求对象的键必须用双引号包裹,字符串值也必须用双引号,而你的字符串里键width没有引号,值用的是单引号,所以JSON.parse无法解析。

以下是几种可行的解决方式:

1. 手动修正格式后用JSON.parse

先处理字符串,把它转换成标准JSON格式,再解析:

// 你的原始输入字符串
const rawStr = "\"{width: '300'}\"";

// 步骤1:去掉外层包裹的双引号
const innerContent = rawStr.substring(1, rawStr.length - 1);

// 步骤2:给对象键添加双引号,把单引号替换为双引号
const validJson = innerContent
  .replace(/(\w+):/g, '"$1":') // 匹配无引号的键,添加双引号
  .replace(/'/g, '"'); // 把单引号换成双引号

// 现在可以正常解析了
const result = JSON.parse(validJson);
console.log(result); // 输出: { width: "300" }

2. 使用eval(仅适用于信任的字符串)

因为这个格式符合JavaScript对象字面量的语法,可以用eval直接解析,但注意:如果字符串来自不可信的外部输入,绝对不要用这个方法,会有安全风险:

const rawStr = "\"{width: '300'}\"";
const innerContent = rawStr.substring(1, rawStr.length - 1);
const result = eval(`(${innerContent})`);
console.log(result); // 输出: { width: "300" }

3. 使用支持宽松JSON的库(如JSON5)

如果你经常处理这类非标准JSON,可以使用JSON5库,它支持无引号键、单引号字符串等宽松语法:

// 先安装JSON5:npm install json5
const JSON5 = require('json5');

const rawStr = "\"{width: '300'}\"";
const innerContent = rawStr.substring(1, rawStr.length - 1);
const result = JSON5.parse(innerContent);
console.log(result); // 输出: { width: "300" }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:42:51