2

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

1 respuesta 1

2

No te funcionan los objetos anidados porque necesitas 2 cosas:

  1. Considerar primero los tipos primitivos
  2. Después, analizar funciones, arreglos y objetos, pero con recursividad, para que cada propiedad y valor sean formateados por la función, sin importar si pertenecen a un objeto o no

Este fragmento de código funciona con tus ejemplos + adiciones en el último; supongo que necesitarás hacer más pruebas y, tal vez, trabajar un poco el formato.

JSON.stringify = function(o) {
    let result = '';
    let oType = typeof o;
    // Considerar primero NULL y tipos primitivos
    if(o === null) {
        result = 'null';
    } else if(oType == 'undefined') {
        result = 'undefined';
    } else if(oType == 'string') {
        result = `"${o}"`;
    } else if(oType == 'symbol') {
        result = `new Symbol("${o.toString()}")`
    } else if(['boolean', 'number', 'bigint'].includes(oType)) {
        result = o.toString();
    }
    // Ahora analizar funciones, arreglos y objetos
    else if(oType == 'function') {
        result = o.toString();
    } else if(o instanceof Array) {
        result = '[';
        // Recorrer para obtener nuevo arreglo y separar por coma
        result += o.map(item => JSON.stringify(item)).join(', ');
        result += ']';
    } else if(o instanceof Object) {
        result = '{';
        let entries = Object.entries(o);
        entries.forEach((entry, i) => {
            const [k, v] = entry;
            // El valor es función y el nombre igual a la clave
            if(typeof v == 'function' && v.name == k) {
                result += JSON.stringify(v);
            } else {
                result += JSON.stringify(k) + ': ' + JSON.stringify(v);
            }
            // Agregar coma si no es el último
            if(i < entries.length - 1) {
                result += ',\n';
            }
        });
        result += '}';
    } else {
        // Opción no considerada
        console.log(o);
    }
    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();
        }
    },
    // Agregados para probar
    arrObj: [
        {nombre: "Triby", hobbies: ['Programar', 'Jugar']}
    ],
    objArr: {
        arr: [6.5, 8.4, 100],
        obj: {
            prop1: {
                prop2: ['a', 'b', 'c']
            }
        }
    },
    bool: true,
    undef: undefined,
    null: null
})); // También funciona

2
  • Muchas gracias @Triby. el 20 jul. 2021 a las 2:54
  • 1
    @Rodrigo, un placer, como siempre. Por cierto, el if(oType == 'function') puede agregarse al arreglo del if previo, pero no quise incluirlo entre los tipos primitivos.
    – Triby
    el 20 jul. 2021 a las 3:02

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.