跳到主要内容

实现

2024年02月05日
柏拉文
越努力,越幸运

一、实现


function JSONStringify(data) {
const isCycle = (obj) => {
const weakSet = new WeakSet();
let detected = false;
const detect = (obj) => {
if (obj != null && typeof obj !== "object") {
return;
}
if (weakSet.has(obj)) {
detected = true;
return detected;
}
weakSet.add(obj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
detect(obj[key]);
}
}
};
detect(obj);
return detected;
};
if (isCycle(data)) {
throw new TypeError("Converting circular structure to JSON");
}
if (typeof data === "bigint") {
throw new TypeError("BigInt value can't be serialized in JSON");
}
const type = typeof data;
const commonKeys = ["undefined", "function", "symbol"];
const getType = (s) => {
return Object.prototype.toString
.call(s)
.replace(/\[object (.*?)\]/)
.toLowerCase();
};
if (type !== "object" || data === null) {
let result = data;
if ([NaN, Infinity, null].includes(data)) {
result = null;
} else if (commonKeys.includes(type)) {
return undefined;
} else if (type === "string") {
result = `"${data}"`;
}
return String(result);
} else if (type === "object") {
if (typeof data.toJSON === "function") {
return JSONStringify(data.toJSON());
} else if (Array.isArray(data)) {
let result = data.map((it) => {
return commonKeys.includes(typeof it)
? "null"
: JSONStringify(it);
});
return `[${result}]`.replace(/'/g, '"');
} else {
if (["boolean", "number"].includes(getType(data))) {
return String(data);
} else if (getType(data) === "string") {
return `"${data}"`;
} else {
let result = [];
Object.keys(data).forEach((key) => {
if (typeof key !== "symbol") {
const value = data[key];
if (!commonKeys.includes(typeof value)) {
result.push(`"${key}":${JSONStringify(value)}`);
}
}
});
return `{${result}}`.replace(/'/g, '"');
}
}
}
}

const obj = {
name: "like",
age: 23,
like: {
ball: [1, 2, 3],
},
};

const result = JSONStringify(obj);
console.log(result)

二、测试