尝试将来自十几个类似网页的数据放到JSON中。页面的结构是定义的,但每个块的数量可能会有所不同:
<h2>Block1</h2>
<p><strong>Title1</strong></p>
<p>content</p>
<!–– the amount of p with content may vary ––>
<p>content</p>
<p>content</p>
<!–– the amount of p with highlighted title may vary ––>
<p><strong>Title_N</strong></p>
<p>content</p>
<p>content</p>
<!–– the amount of h2 blocks may vary ––>
<h2>Block_N</h2>
<p><strong>Other_Title</strong></p>
<p>content</p>
我试图像下面这样形成一个JSON,但是当它们在同一层次结构中,并且它们的数量是不确定的时候,在标签之间迭代标签有困难:
result.push({
BlockName: $('.frame h2').text(),
BlockContent:[{
TitleName1: $('.frame p>strong:nth-of-class(1)').text(),
TitleContent1[{
Content1:$('.frame p>strong:nth-of-class(1)').nextUntil($('.frame p>strong:nth-of-class(2)')).each(///),
Content2:$('.frame p>strong:nth-of-class(2)').nextUntil($('.frame p>strong:nth-of-class(3)')).each(///)),
///
ContentN:$('.frame p>strong:nth-of-class(Last-1)').nextUntil($('.frame p>strong:nth-of-class(LastOne)')).each(///),
}],
///
}],
})所以我甚至不能指定我应该收集每个条目的数据的确切的标签。有没有办法不把所有标签的索引都存储在各自的变量中?
例如-降低created flat JSON中某些条目的层次结构:like this
我应该尝试什么方法?
感谢您的帮助,谢谢!
发布于 2017-12-23 00:56:01
我写了一个肮脏的例子,你可以从中获得灵感,输出变量应该符合你的规范!
我使用js遍历DOM的所有节点,并使用节点的类型(HTMLParagraphElement等)确定它是块的名称、标题还是内容。
Array.prototype.slice.call(dom.children).forEach((node) => {
if (node instanceof HTMLHeadingElement) {
if (Object.keys(currentBlock).length !== 0) {JSFiddle:https://jsfiddle.net/z7dmwd7d/
https://stackoverflow.com/questions/47940300
复制相似问题