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

JavaScript中如何将Map及含Map的实体转换为JSON字符串?

解决JavaScript中Map转JSON及包含Map的对象序列化问题

为什么直接序列化Map会得到空对象?

JSON.stringify() 只识别对象的可枚举自有属性,而Map的键值对并非存储在对象自身的属性中,因此直接序列化Map会返回 {}。


单个Map转JSON的两种方法

方法1:转成普通对象(推荐,适合键为字符串的场景)

使用 Object.fromEntries() 将Map的键值对转换为普通对象,再进行序列化:

let m = new Map<string, string>();
m.set("a", "b");
const plainObj = Object.fromEntries(m);
console.log(JSON.stringify(plainObj)); // 输出: {"a":"b"}

方法2:转成二维数组(适合键为非字符串类型的场景)

如果需要保留键的原始类型(比如数字、Symbol),可以把Map转成二维数组:

let m = new Map<string, string>();
m.set("a", "b");
const mapArr = Array.from(m);
console.log(JSON.stringify(mapArr)); // 输出: [["a","b"]]

解析时可以用 new Map(解析后的数组) 还原成Map。


包含Map的对象(如TexFileModel)序列化方案

TypeScript的接口仅为类型定义,编译后是普通JavaScript对象,需要手动处理其中的Map:

1. 针对特定对象的转换

写一个简单的转换函数,把对象中的Map转成普通对象:

export interface TexFileModel { 
    id: number; 
    m: Map<string,string>
}

const model: TexFileModel = {
    id: 1,
    m: new Map([["a", "b"]])
};

function serializeTexFileModel(model: TexFileModel) {
    return {
        ...model,
        m: Object.fromEntries(model.m)
    };
}

console.log(JSON.stringify(serializeTexFileModel(model))); 
// 输出: {"id":1,"m":{"a":"b"}}

2. 通用递归转换(支持嵌套Map)

如果对象中有多个Map或嵌套Map,用递归函数批量转换:

function convertMapsToPlainObjects(obj: any): any {
    if (obj instanceof Map) {
        return Object.fromEntries(obj);
    }
    if (typeof obj === 'object' && obj !== null) {
        return Object.fromEntries(
            Object.entries(obj).map(([key, val]) => [key, convertMapsToPlainObjects(val)])
        );
    }
    return obj;
}

// 使用示例
const model: TexFileModel = { id: 1, m: new Map([["a", "b"]]) };
console.log(JSON.stringify(convertMapsToPlainObjects(model)));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:27:21