如何将文件读取的转义JSON转为TypedJSON与class-transformer可解析对象
解决带转义符的JSON转换问题
核心思路
从文件读取到的带转义符内容本质是JSON字符串的字符串形式,只要先把它解析成标准JSON对象,就能正常交给class-transformer或TypedJSON处理。
具体操作步骤
1. 读取文件原始内容
用文件读取API(比如Node.js的fs.readFileSync/fs.promises.readFile)拿到文件里的原始字符串,此时内容会是带转义符的格式,例如:
// 读取到的带转义内容示例 const escapedJsonStr = "{\"name\":\"Aerosol\",\"productId\":\"QSRT001\",\"description\":\"A great product, air purifier\"}";
2. 解析转义字符串为标准对象
用原生JSON.parse()处理这个带转义的字符串,直接得到干净的目标对象:
const productJson = JSON.parse(escapedJsonStr); // 此时productJson结构和你直接声明的完全一致: // { // name: 'Aerosol', // productId: 'QSRT001', // description: 'A great product, air purifier' // }
3. 交给目标库处理
拿到标准对象后,就可以和直接声明的对象一样使用class-transformer或TypedJSON了:
// TypedJSON示例(假设已有Product类) const product = TypedJSON.parse(productJson, Product); // class-transformer示例 const product = plainToClass(Product, productJson);
特殊场景处理
如果遇到多层转义(比如转义符本身也被转义成\\"),可以多执行一次JSON.parse():
// 多层转义的内容示例 const doubleEscapedStr = "\\{\\\"name\\\":\\\"Aerosol\\\"\\}"; const singleEscapedStr = JSON.parse(doubleEscapedStr); // 先解析成单层转义字符串 const productJson = JSON.parse(singleEscapedStr); // 再解析成最终对象
内容的提问来源于stack exchange,提问作者BreenDeen
相关产品推荐
相关产品推荐

