使用JavaScript从字符串中提取flags与Preference对象转为JSON
提取并转换script标签中的flags与Preference对象为JSON
需求说明
从script标签内的字符串代码中,提取flags和Preference对象,并转换为标准JSON格式。原始代码示例:
flags = { "onFlag" : true, "offFlag" : false }; Preference = { "onPreference" : true, "offPreference" : false };
方法一:正则表达式提取 + JSON格式化
通过正则匹配目标对象的定义结构,提取对象内容后修正语法,再转换为JSON。
代码示例
// 假设script标签内容已存入该变量 const scriptContent = `flags = { "onFlag" : true, "offFlag" : false }; Preference = { "onPreference" : true, "offPreference" : false };`; // 匹配flags对象的正则 const flagsRegex = /flags\s*=\s*({[\s\S]*?});/; // 匹配Preference对象的正则 const preferenceRegex = /Preference\s*=\s*({[\s\S]*?});/; // 提取匹配结果 const flagsMatch = scriptContent.match(flagsRegex); const preferenceMatch = scriptContent.match(preferenceRegex); if (flagsMatch && preferenceMatch) { // 修正语法:补全属性名引号、处理布尔值格式 const flagsStr = flagsMatch[1] .replace(/(\w+)\s*:/g, '"$1":') // 给无引号的属性名加引号 .replace(/:\s*(true|false)/g, ': $1'); // 保留布尔值原生格式 const preferenceStr = preferenceMatch[1] .replace(/(\w+)\s*:/g, '"$1":') .replace(/:\s*(true|false)/g, ': $1'); // 转换为JSON对象 try { const flagsJson = JSON.parse(flagsStr); const preferenceJson = JSON.parse(preferenceStr); console.log('flags JSON:', flagsJson); console.log('Preference JSON:', preferenceJson); } catch (error) { console.error('JSON解析失败:', error); } }
方法二:沙箱环境执行(仅适用于可信代码)
如果确定script内容安全,可以在隔离的沙箱中执行代码,直接获取对象后转换为JSON,避免正则处理的语法兼容问题。
代码示例
const scriptContent = `flags = { "onFlag" : true, "offFlag" : false }; Preference = { "onPreference" : true, "offPreference" : false };`; // 创建沙箱,避免污染全局变量 const sandbox = {}; // 用自执行函数包裹代码,将对象存入沙箱 eval(`(function() { ${scriptContent} sandbox.flags = flags; sandbox.Preference = Preference; })()`); // 转换为JSON对象 const flagsJson = JSON.parse(JSON.stringify(sandbox.flags)); const preferenceJson = JSON.parse(JSON.stringify(sandbox.Preference)); console.log('flags JSON:', flagsJson); console.log('Preference JSON:', preferenceJson);
注意事项
- 优先检查原始代码的语法正确性,比如示例中
"offFlag : false缺少闭合引号这类错误,会直接导致JSON解析失败,需提前修正。 - 处理不可信来源的代码时,禁止使用
eval,建议使用AST解析库(如acorn)遍历语法树提取对象,避免代码注入风险。
内容的提问来源于stack exchange,提问作者Gautham Shetty
相关产品推荐
相关产品推荐

