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

Node.js中如何将对象数组形式的字符串转换为JSON?

在Node.js中将非标准对象数组字符串转换为JSON

嘿,我来帮你搞定这个问题!你给出的字符串是一个类似对象数组的结构,但它并不符合JSON的规范——最核心的问题是对象的键没有被双引号包裹,而JSON格式严格要求所有键必须是双引号包裹的字符串。下面是两种在Node.js环境下的处理方案:

方法一:正则修正 + JSON.parse(推荐,更安全)

这种方法先通过正则表达式给缺失双引号的键补上引号,再用标准的JSON.parse方法解析成JSON对象,完全规避了安全风险。

let data = "[{Date: 2002,Entity Taking Action: Maryland Board ,Action Taken: Reprimand},{Date: 2002,Entity Taking Action: Massachusetts Board,Action Taken: Consent order because of Maryland Board},{Date: 2007,Entity Taking Action: North Carolina Medical Board,Action Taken: Consent order because of Maryland Board action},{Date: 2013,Entity Taking Action: NC Medical Board,Action Taken: Letter of concern for not reporting previous NC consent order on reactivation of NC licence}]";

// 用正则匹配所有由字母和空格组成的键,给它们加上双引号
const validJsonStr = data.replace(/([a-zA-Z\s]+):/g, '"$1":');

try {
  // 解析为JSON对象数组
  const jsonData = JSON.parse(validJsonStr);
  console.log('转换后的JSON对象:', jsonData);
  
  // 如果需要JSON字符串,再用JSON.stringify转换
  const jsonString = JSON.stringify(jsonData, null, 2);
  console.log('格式化后的JSON字符串:\n', jsonString);
} catch (error) {
  console.error('转换失败:', error.message);
}

正则说明

/([a-zA-Z\s]+):/g 会匹配所有由英文字母和空格组成的键(比如Date、Entity Taking Action),然后把它们替换成"键名":的格式,让字符串符合JSON语法要求。

方法二:使用eval(仅适用于完全可信的字符串来源)

如果你能100%确定这个字符串的来源是安全的,不会包含恶意代码,可以用eval直接把字符串解析成JavaScript对象数组,再转换成JSON。但强烈不推荐在不可信的场景下使用,因为eval会执行字符串中的任意代码,存在安全隐患。

let data = "[{Date: 2002,Entity Taking Action: Maryland Board ,Action Taken: Reprimand},{Date: 2002,Entity Taking Action: Massachusetts Board,Action Taken: Consent order because of Maryland Board},{Date: 2007,Entity Taking Action: North Carolina Medical Board,Action Taken: Consent order because of Maryland Board action},{Date: 2013,Entity Taking Action: NC Medical Board,Action Taken: Letter of concern for not reporting previous NC consent order on reactivation of NC licence}]";

try {
  // 解析为JavaScript对象数组
  const objArray = eval(data);
  // 转换为格式化的JSON字符串
  const jsonString = JSON.stringify(objArray, null, 2);
  console.log('转换后的JSON字符串:\n', jsonString);
} catch (error) {
  console.error('处理失败:', error.message);
}

总结

优先选择方法一,它既安全又符合JSON标准规范。只有在你完全信任输入字符串的情况下,才考虑使用方法二。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:52:34