0

Tengo un objeto json creado con las etiquetas y atributos de los elementos html. Ahora que ya tengo el json quiero volver a reconstruir todo el html recorriendo el json. Cualquier sugerencia me seria de gran ayuda.

<div class='container'>
    <div id='padre'>
        <p>texto</p>
        <div id='hijo'>
            <h2>texto</h2>
            <div id='nieto'>
            </div>
            <div id='nieto2'>
            </div>
            <div id='nieto3' style='background: red;'>
                <p>texto</p>
            </div>
        </div>
    </div>
    <div id='padre'>
        <div id='hijo'>
            <p>texto</p>
        </div>
    </div>
    <div id='padre'>
        <div id='hijo'>
            <p>texto</p>
        </div>
    </div>
</div>    

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script>

    var obj={};
    var body=document.body
    var element = document.body
    getAllChild(element,obj)

    console.log(obj)
    var json=JSON.stringify(obj);

    //showObject(json)

    function showObject(json){
        //convertimos en json en un objeto
        var obj = JSON.parse(json)
        console.log(obj.children)
        if(obj.children.length!=0){
            for( var i = 0; i <= obj.children.length; i++ ){
                document.body.innerHTML = obj.children[i].text
            }
        }else{
            console.log('no hijos')
        }
    }

    function getAllChild(element,obj){
        var attr = [];
        obj.tag=element.localName;
        obj.attr=attr;
        obj.name=element.name;
        obj.text = element.innerText;

        $(element.attributes).each(function(){
            var data = {'attr':this.name, 'val':this.value }
            attr.push(data)
        })

        if(element.children.length!=0){
            obj.children=[];
            [].forEach.call(element.children,(val,i)=>{
                obj.children[i]={};
                getAllChild(val,obj.children[i]);
            });
        }
    }


</script>

1
  • [json2html.com/] Esta página contiene un convertidor de JSON a HTML, que puedes aplicar sobre tu página (plugin jQuery). Puede que te sirva el 23 may. 2018 a las 8:18

1 respuesta 1

0

Podrías probar algo así:

    function callback(req)
{
    var response = eval("("+req.responseText+")");
    response = response.response;

    createElementsFromJSON(response, document.body);
}

function createElementsFromJSON(json, parent)
{
    for(var i in json)
    {
        var object = json[i];

        var obj = document.createElement(object.element);

        for(var tag in object)
            if (tag!="children"&&tag!="element")
                obj.setAttribute(tag, object[tag]);

        parent.appendChild(obj);

        if (typeof(object.children)=="object")
            createElementsFromJSON(object.children, obj);
    }
}

Para un JSON de la siguiente forma:

{
    "response":
    [
        {
            "element":"div",
            "id":"james",
            "children":
            [
                {
                    "element":"h1",
                    "id":"bob",
                    "innerHTML":"bobs content",
                },
                {
                    "element":"h2",
                    "id":"rob",
                    "innerHTML":"robs content",
                },
                {
                    "element":"p",
                    "innerHTML":"some random text",
                },
            ],
        },
        {
            "element":"div",
            "id":"alex",
            "innerHTML":"this is a test message in a div box",
        },
    ]
}
1
  • Lo único que el attr que tienes guardando el tipo y valor de atributo irían directamente en el objeto json, no estarían encapsulados en otro objeto. el 23 may. 2018 a las 8:23

Tu Respuesta

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

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