Create JSON from an HTML block with its attributes


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 = []


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

      //obtiene los atributos de todos los divs padres
              var data = {'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

              var data = {'name', 'value':this.value}


     //var arr = JSON.stringify(obj)

  gen4('.story div')
<!doctype html>
<html lang="es">
    <!-- 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="" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

    <title>test story</title>
    <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 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 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.
            <div class="col-md-6">
                <button> generar </button>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>



asked by Marcos Mauricio 10.05.2018 в 04:13

1 answer


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){

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.


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

    var json=JSON.stringify(obj);

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){

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


    var json=JSON.stringify(arr);

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

answered by 16.05.2018 / 03:47