如何将JSON中存储的类型名字符串转换为JavaScript实际数据类型?
问题
我有一个根据属性数据类型表现不同的程序,目前通过以下方式设置数据类型:
const myObject = new MyObject(); myObject.numberType = number; myObject.main();
我希望从JSON文件读取数据类型,但JSON无法直接存储字面量数据类型,只能存储对应类型的字符串,比如:
{ "type1": "number", "type2": "string" }
我想把程序改成下面的形式,同时保持原有行为:
import types from './types.json' assert { type: "json" }; // const types = require('./types.json'); // ES5环境下使用 const myObject = new MyObject(); myObject.numberType = types['type1']; // 此行需要修改 myObject.main();
最小可复现示例(MRE)
JSON文件
{ "type1": "number", "type2": "string" }
JavaScript代码
import types from './types.json' assert { type: "json" }; async function main () { const type1 = typeof (types['type1']); const type2 = typeof (types['type2']); console.log(type1); console.log(type2); }; main();
当前输出
string string
期望输出
number string
我需要把实际数据类型存入变量,而不只是存储对应类型的字符串——本质是想在JSON文件中记录数据类型,让程序读取后转换为实际的类型。
解决方案
要实现这个需求,核心是创建类型映射表,把JSON中的字符串类型名对应到JavaScript的原生类型构造函数或特殊类型值上。
方法1:基础类型映射(适配MRE场景)
创建映射表将字符串类型名转换为JS原生类型,同时验证输出匹配期望结果:
import types from './types.json' assert { type: "json" }; // 定义类型映射规则 const typeMap = { number: Number, string: String, boolean: Boolean, array: Array }; async function main () { // 从映射表获取实际类型构造函数 const actualType1 = typeMap[types['type1']]; const actualType2 = typeMap[types['type2']]; // 输出实际类型名(匹配期望输出) console.log(typeof new actualType1()); // 输出number console.log(typeof new actualType2()); // 输出string }; main();
方法2:适配MyObject场景
如果你的MyObject需要接收原生类型构造函数(比如Number),直接通过映射表转换赋值即可:
import types from './types.json' assert { type: "json" }; const typeMap = { number: Number, string: String }; const myObject = new MyObject(); // 将JSON字符串转换为实际类型构造函数 myObject.numberType = typeMap[types['type1']]; myObject.main();
方法3:支持特殊类型(null/undefined)
如果需要处理null、undefined这类无法通过构造函数表示的特殊类型,可以扩展映射逻辑:
const typeMap = { number: Number, string: String, null: null, undefined: undefined }; // 封装类型转换函数 const getActualType = (typeStr) => { const targetType = typeMap[typeStr]; // 对于null/undefined直接返回值,其余返回构造函数 return targetType === null || targetType === undefined ? targetType : targetType; };
关键说明
- JSON仅支持存储字符串、数字、布尔值、null、数组和对象,无法直接保存JS原生类型构造函数,因此必须通过映射转换实现需求。
- 确保JSON中的类型字符串与映射表的键严格匹配(大小写、拼写一致),避免转换失败。
- 如果需要判断变量的实际类型,可通过
typeof new 构造函数()得到对应类型的字符串。
内容的提问来源于stack exchange,提问作者Sam Germain
相关产品推荐
相关产品推荐

