将HTML DOM结构转换为JSON [英] convert HTML DOM structure to JSON
问题描述
我在此上浪费了很多时间..递归部分非常虚幻.
对于未知深度的给定HTML结构,我需要转换为JSON.
(我从我正在构建的某些YAML i18n翻译系统中使用此代码)
I have wasted so much time on this..the recursion part is quite illusive.
for a given HTML structure, of unknown depth, I need to convert to JSON.
(I use this from some YAML i18n translation system I am building)
我的一般想法是深入研究直到找到INPUT
,然后创建一个
具有span.innerHTML/input.value
的键/值的对象,并返回
对象,因此它将是最后到达<span class="title">
的KEY的值.
my general idea is to go deep until it finds the INPUT
, then create an
object with the key/value of the span.innerHTML/input.value
, and return that
object, so it will be the VALUE of a KEY that is the last <span class="title">
reached.
(是的,开发有点复杂,但非常有趣)
(Yes, it's a bit complicated but very interesting to develop)
JSBIN游乐场-实时代码示例
我的递归函数无法正常工作,无法输出所需的JSON ...
<ul>
<li>
<span class="title">footer</span>
<ul>
<li>
<span>statement</span>
<input type="text" value="xxx">
</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>
{
footer : {
statement : 'xxx'
},
landing : {
page_title : 'yyy',
page_sub_title : 'xxx',
pricing : {
title : 'aaa',
cost : 'xxx'
}
}
}
推荐答案
如果您可以说服自己使用jQuery,请尝试此:
If you can convince yourself to using jQuery, try this:
function helper(root) {
var result = {};
$('> ul > li > span', root).each(function () {
result[$(this).text()] = $(this).hasClass('title') ? helper($(this).parent()) : $(this).next('input').val();
});
return result;
}
console.log(helper('body'));
这篇关于将HTML DOM结构转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!