Intento convertir un objeto a un string, usando el método JSON.stringify
, este pierde las funciones que contiene adentro
console.log(JSON.stringify({
any:"..",
func() {
console.log("a");
}
})); // {"any":".."}
Esto porque las funciones no son válidas en una estructura JSON. Intenté sobrescribir el método JSON.stringify
y funciona, pero cuando hay múltiples objetos anidados, los valores de algunas keys son [object Object]
.
Esto es lo que tengo
JSON.stringify = function(o) {
const isObject = o => o && Object.prototype.toString.call(o).toLowerCase() === "[object object]";
let result = '';
if (o instanceof Array) {
result += "[";
o.forEach((e, i) => {
if (isObject(e) || e instanceof Array) {
result += JSON.stringify(e) + (i === o.length - 1 ? "]" : ", ");
} else {
result += (typeof e === "string" ? `"${e}"` : e) + (i === o.length - 1 ? "]" : ", ");
}
});
return result;
} else if (isObject(o)) {
result += "{";
Object.entries(o).forEach((entry, i) => {
const [k, v] = entry;
if (typeof v === "string") {
result += i === Object.keys(o).length - 1 ? `"${k}":"${v}"` : `"${k}":"${v}", `;
} else if (typeof v === "function") {
if (v.toString().startsWith("function") || v.toString().startsWith("(")) {
result += i === Object.keys(o).length - 1 ? `"${k}":${v}` : `"${k}":${v}, `;
} else {
result += i === Object.keys(o).length - 1 ? `${v}` : `${v}, `;
}
} else if (v instanceof Array || isObject(v)) {
result += i === Object.keys(o).length - 1 ? `"${k}":${JSON.stringify(v)}` : `"${k}":${v}, `;
} else {
result += i === Object.keys(o).length - 1 ? `"${k}":${v}` : `"${k}":${v}, `;
}
});
result += "}";
return result;
}
}
console.log(JSON.stringify({
a: "b",
test() {
return "b";
}
})); // Funciona
console.log(JSON.stringify({
a: "b",
anidado: {
prueba() {
return "b";
}
}
})); // Funciona
console.log(JSON.stringify({
json: {
url: "/json/index"
},
json2: {
url: "/json/json2"
},
events: {
hover() {
e.target.style.color = "red";
}
},
numArray: [1, 2, 3, 4, 5],
test: {
conf: {
attributes: true
},
then(mutation, observe) {
console.log(mutation);
observe.disconnect();
}
}
})); // No funciona