JavaScript 中从 JSON 字符串动态解析并获取原生数据类型

7次阅读

JavaScript 中从 JSON 字符串动态解析并获取原生数据类型

本文讲解如何将 json 文件中存储的类型名称字符串(如 “number”、”String”)安全、准确地映射为对应的 javascript 原生构造函数或类型标识,从而在运行时动态创建实例或执行类型相关逻辑。

javaScript 中,jsON 仅支持有限的原始数据类型(string、number、BooleanNULLArrayObject),无法直接序列化 Number、String、date 等构造函数或 typeof 返回的类型标识。因此,当你在 json 中写 “type1”: “number” 时,它只是一个普通字符串;typeof types.type1 永远返回 “string” —— 这正是你观察到当前输出全为 string 的根本原因。

要实现“从字符串还原为可使用的类型”,关键不在于“解析类型名”,而在于建立一个受控的、显式的字符串 → 构造函数/类型行为映射表。以下是推荐的工程化方案:

✅ 正确做法:使用白名单映射表(安全且可维护)

// typeMap.js const TYPE_MAP = {   'number': Number,   'string': String,   'boolean': Boolean,   'object': Object,   'array': Array,   'date': Date,   'json': JSON,   // 可扩展:'custom-user': UserClass };  export function stringToType(typeName) {   const Constructor = TYPE_MAP[typeName.toLowerCase()];   if (!Constructor) {     throw new Error(`Unsupported type name: "${typeName}"`);   }   return Constructor; }
// main.js import types from './types.json' assert { type: 'json' }; import { stringToType } from './typeMap.js';  class MyObject {   constructor() {     this.numberType = null;   }   main() {     // ✅ 正确:获取 Number 构造函数,可用于 new Number() 或 typeof 判断逻辑     this.numberType = stringToType(types.type1); // → Number     console.log(this.numberType === Number); // true     console.log(typeof new this.numberType(42)); // "number"      // ✅ 同理处理其他类型     const StringType = stringToType(types.type2); // → String     const s = new StringType('hello');     console.log(s instanceof String); // true   } }  const myObject = new MyObject(); myObject.main();

⚠️ 注意事项与常见误区

  • 不要使用 eval() 或 Function() 动态执行字符串(如 eval(‘Number’)):存在严重 xss 和代码注入风险,且违反 CSP 安全策略,绝对禁止。
  • 不要依赖 window[typeName] 或 globalThis[typeName]:number 不是全局变量,Number 才是;大小写、拼写错误极易导致 undefined,且 Node.js 与浏览器环境全局对象不一致。
  • 始终使用显式白名单(如 TYPE_MAP):确保仅允许预期类型,便于类型校验、ide 提示和 typescript 集成。
  • 区分“类型构造函数”与“类型判断”:若你实际需要的是 typeof value === ‘number’ 这类判断,可封装为:
    export function isType(value, typeName) {   const type = typeName.toLowerCase();   switch (type) {     case 'number': return typeof value === 'number' && !isNaN(value);     case 'string': return typeof value === 'string';     case 'boolean': return typeof value === 'boolean';     case 'array': return Array.isArray(value);     case 'object': return value !== null && typeof value === 'object' && !Array.isArray(value);     default: return false;   } }

? 总结

JSON 是数据交换格式,不是代码载体。将类型信息以字符串形式存于 JSON 是合理的设计(解耦配置与逻辑),但必须通过显式、安全、可测试的映射层将其桥接到运行时类型系统。本文提供的 stringToType 白名单方案兼顾安全性、可读性与可扩展性,适用于配置驱动型应用(如表单生成器、序列化策略、DSL 解析器等)。切记:永远避免动态代码执行,拥抱明确契约。

text=ZqhQzanResources