Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
  <title>DOM to JSON</title>
  <!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <style>
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
    <ul>
    <li>
        <span class="title">footer</span>
        <ul>
            <li>
                <span>statement</span>
                <input type="text" value="xxxx">
            </li>
        </ul>
    </li>
    <li>
        <span class="title">landing</span>
        <ul>
            <li>
                <span>page_title</span>
                <input type="text" value="yyy">
            </li>
            <li>
                <span>page_sub_title</span>
                <input type="text" value="xxx">
            </li>
            <li>
                <span class="title">pricing</span>
            <ul class="level11">
                <li>
                    <span>title</span>
                    <input type="text" value="aaa">
                </li>
                <li>
                    <span>cost</span>
                    <input type="text" value="xxx">
                </li>
            </ul>
            </li>
        </ul>
    </li>
    </ul>
</body>
</html>
 
var out = {
    footer : {
        statement : 'xxxx'
    },
    landing : {
        page_title : 'yyy',
        page_sub_title : 'xxx',
        pricing : {
            title : 'aaa',
            cost : 'xxx'
        }
    }
};
var ul = document.body.firstElementChild;
var data = extractKeyValue({}, ul)[1];
function extractKeyValue(span, thing) {
  if (thing.tagName === "INPUT") {
      return [span.textContent, thing.value];
  } else {
    var obj = {};
    [].forEach.call(thing.children, function (li) {
      var span = li.firstElementChild;
      var thing = span.nextElementSibling;
      var tuple = extractKeyValue(span, thing);
      obj[tuple[0]] = tuple[1];
    });
    return [span.textContent, obj];
  }
}
 
console.log(data);
console.log(JSON.stringify(data) === JSON.stringify(out));
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers