Create JSON from an HTML block with its attributes

2

I need to create a script with jquery that reads me an entire html block and get me the html tag, its attributes and its content, this must be done with the children tag, then create a json object with all the data.

This what I've been testing.

function gen4(block){
    
  var attr = []
  var child = []

  var attr2 = []
  var child = []

  $(block).each(function(){

      // objeto       
      var obj = new Object()
      obj.tag = $(this).prop('tagName')
      obj.attr = attr
      obj.child = child


      //obtiene los atributos de todos los divs padres
      $(this.attributes).each(function(index){
          if(this.specified){
              var data = {'name':this.name, 'value':this.value}
              attr.push(data )
          }

      })

      //obtiene los atributos de todos los divs hijos
      $(this).children().each(function(index, element){

          var obj2 = new Object()
          obj2.tag = $(this).prop('tagName')
          obj2.attr = attr2
          obj2.child = child

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

     console.log(obj)  

     //var arr = JSON.stringify(obj)
     //console.log(arr)
  })

}
$(document).ready(function(){    
  gen4('.story div')
})
<!doctype html>
<html lang="es">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

    <title>test story</title>
  </head>
  <body>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <div id="story" class="story">
                    <div class='block-title' style="background:red;color:white;">
                        <h2 class='title' style="font-weight:bold;"> title </h2>
                    </div>
                    <div class='block-image' data-value="value1" data-value2="value2">
                        <img class='foto' src="foto.png" alt=":)" />
                        <div class='hijo'>
                            <div class='nieto'>
                                <p> texto </p>
                            </div>
                        </div>
                    </div>
                    <div class='block-content'>
                        <p class='texto'>
                            Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de textos y los mezcló de tal manera que logró hacer un libro de textos especimen. No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la creación de las hojas "Letraset", las cuales contenian pasajes de Lorem Ipsum, y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker, el cual incluye versiones de Lorem Ipsum.
                        </p>
                    </div>            
                </div>
            </div>
            <div class="col-md-6">
                <button> generar </button>
            </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://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" 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>

  </body>

 <script>

 </script> 
</html>
    
asked by Marcos Mauricio 10.05.2018 в 04:13
source

1 answer

1

To capture all the elements contained within an html element there are several ways depending on what you want to do.

1) if what you want to do is obtain a structure in which YES parent child relationship you can use a recursive function.

    var obj={};
    var body=document.body;
    function getAllChild(element,obj){
        obj.tag=element.localName;
        obj.value=element.value;
        obj.name=element.name;
        if(element.children.length!=0){
            obj.children=[];
            [].forEach.call(element.children,(val,i)=>{
                obj.children[i]={};
                getAllChild(val,obj.children[i]);
            });
        }
    }

This function creates an object with all the children of the element (body) and structures it as a family tree. Receive as parameters an element and an empty object.

    getAllChild(body,obj);
    console.log(obj);

To convert the JSON object you can use the stringify function.

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

Since many elements do not have value or name , the generated object will have these values undefined , it is already a matter of modifying the example to save existing properties or to save only elements with those attributes.

2) If the parent child relationship between elements does not matter, a simple loop can be made:

    var arr=[];
    var body=document.body;
    function getAllChild(element,arr){
        [].forEach.call(element.querySelectorAll('*'),(val)=>{
            arr.push({tag:val.localName,value:val.value,name:val.name});
        });
    }

In this case element.querySelectorAll('*') selects the elements contained in the element, regardless of whether they are children or are within them ...

    getAllChild(body,arr);
    console.log(arr);

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

This question has its days but I hope it serves the community ...

    
answered by 16.05.2018 / 03:47
source