您可以使用JSON.parse reviver
函数
Note: this code may be more complex than needed, but, I tried to make it flexible enough to handle types of data, not just 100
const reviver = (key, value) => {
const defaultReviver = (data, type) => new globalThis[type](data);
const revivers = {
// new Buffer is deprecated, so use Buffer.from
Buffer: data => Buffer.from(data),
//
// add any other exceptions (I can't think of any)
};
if (typeof value !== "object") {
return value;
}
const keys = Object.keys(value);
if (keys.length !== 2 || !keys.includes("type") || !keys.includes("data")) {
return value;
}
// only concern ourselves with global classes with `.toJSON`
// to be honest, perhaps Buffer is the only one
// but, this code should be flexible
if (typeof globalThis[value.type]?.prototype?.toJSON !== 'function') {
return value;
}
try {
const fn = revivers[value.type] || defaultReviver;
return fn(value.data, value.type);
} catch {
return value;
}
};
只需一次更改即可完成部分代码
const buf = Buffer.from("Calling Mr. Jones", "utf8");
const ob = { b: buf };
const obS = JSON.stringify(ob);
const obExtracted = JSON.parse(obS, reviver); // use reviver
console.log(obExtracted.b.toString());