将DOM结构转换为JSON [英] convert DOM structure to JSON
问题描述
我浪费了太多时间在这个...递归部分是非常虚幻的。
对于给定的HTML结构,b
,深度未知,我需要转换为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
的键/值创建
对象,并返回
对象,因此它将是KEY的VALUE,即最后< span class =title>
已到达。
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游乐场 - 实时代码示例
JSBIN playground - live code example
我可以不能让我的递归函数正常工作,输出我想要的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'));
这篇关于将DOM结构转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!