convert an HTML DOM structure (or cloned) to JSON by using JavaScript, JQuery possible -


this question has answer here:

i saw question here before (here , here) still haven't seen solution. since asked in 2011 thought might try myself :)

i need convert whole html structure json.

structure:

<body>  <div class="container">      lorem ipsum dolor  </div>  <h1>this heading 1      <div class="footer">         tessssst      </div>  </h1>  </body>

desired json:

{      "body": {          "div": {              "text": "loremipsumdolor",              "class": "container"          },          "h1": {              "div": {                  "text": "tessssst",                  "class": "footer"              }          }      }  }

are there nice methods except writing vanilla code? thanks.

try utilizing $.map()

var res = {};  var elems = $.map($("body"), function(el, index) {    res[el.tagname] = $(el).children().map(function(i, elem) {      var obj = {};      var name = elem.tagname;      if (!$(elem).children().length) {        obj[name] = {          "text": elem.textcontent,          "class": elem.classname        };      } else {        var _elems = $.map($(elem).children(), function(val, key) {          var _obj = {};          _obj[val.tagname] = {            "text": val.textcontent,            "class": val.classname          };          return _obj        });        obj[name] = {          "text": elem.textcontent,          "class": elem.classname        };        _elems.foreach(function(v, k) {          var _name = object.keys(v)[0];          obj[name][_name] = {            "class": v[_name]["class"],            "text": v[_name]["text"]          }        })      }      return obj    }).get();    return res  });    console.log(elems);    $("<pre />", {"text": json.stringify(elems, null, 2)})  .prependto("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>    <body>    <div class="container">      lorem ipsum dolor    </div>    <h1>this heading 1      <div class="footer">         tessssst      </div>  </h1>  </body>


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -