【问题标题】:Parse HTML into a specific JSON object将 HTML 解析为特定的 JSON 对象
【发布时间】:2016-03-26 12:29:35
【问题描述】:

如何从一些 HTML 创建特定的 JSON 对象?

示例

这是格式很好的HTML page(从markdown 渲染)。我想为页面上的部分创建 JSON 表示。

所以每个“h2”都是一个标题。后面的每个 h3、h4 或 h5 都是一个字幕

鉴于此 HTML:

<h2><a href="#charts">Charts</a></h2>
<ul>...</ul>
<h5><a href="#third-party">Third Party</a></h5>
<ul>...</ul>
<h5><a href="#reusable-chart-frameworks">Reusable Chart Frameworks</a></h5>
<ul>...</ul>
<h2><a href="#maps">Maps</a></h2>
<h5><a href="#third-party-1">Third Party</h5>
...

返回此 JSON:

[
  {
    "title": {
      "text": "Charts",
      "href": "#charts"
    }
    "subtitles": [
      {
        "text": "Third Party",
        "href": "#third-party"
      },
      {
        "text": "Reusable Chart Frameworks",
        "href": "#reusable-chart-frameworks"
      }
    ]
  },
  {
    "title": {
      "text": "Maps",
      "href": "#maps"
    },
    "subtitles": ]
      "text": "Third Party",
      "href": "#third-party-1"
    ]
  },
  ...
]

我考虑过的解决方案

看起来 jQuery 可以帮上大忙。如果这些项目是嵌套的,那么很容易做到$('h2').each(...) 并且只需遍历每个部分,将其附加到我的 JSON 对象。但是这里没有嵌套,只有兄弟姐妹。有什么想法吗?

【问题讨论】:

标签: javascript jquery json


【解决方案1】:

另一种解决方案是映射它:

var mappedJSON = $('h2').map(function() {
  var $selfA = $(this).children('a');
  var subtiles = $(this).nextUntil('h2').filter(':header').children('a').map(function() {
    return {
      "text": $(this).text(),
      "href": $(this).attr('href')
    }
  }).get();
  return {
    "title": {
      "text": $selfA.text(),
      "href": $selfA.attr('href')
    },
    "subtitles": subtiles
  };
}).get();

console.log(mappedJSON);
$('<pre/>').appendTo($('body').empty()).text(JSON.stringify(mappedJSON, null, "\t"));
pre {
  tab-size: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2><a href="#charts">Charts</a></h2>
<ul>...</ul>
<h5><a href="#third-party">Third Party</a></h5>
<ul>...</ul>
<h5><a href="#reusable-chart-frameworks">Reusable Chart Frameworks</a></h5>
<ul>...</ul>
<h2><a href="#maps">Maps</a></h2>
<h5><a href="#third-party-1">Third Party</h5>

【讨论】:

    【解决方案2】:

    这是一个仅依赖于 jQuery 的 .nextUntil() 函数的解决方案。

    var sections = [];
    
    var eTitles = $('article').find('h2');
    
    $(eTitles).each(function(){
      var section = {
        "title": {
          "text": $(this).text(),
          "href": $(this).find('a').attr('href')
        },
        "subtitles": []
      }
    
      var eSubtitles = $(this).nextUntil('h2').filter('h3, h4, h5');
    
      $(eSubtitles).each(function(){
        var subtitle = {
          "text": $(this).text(),
          "href": $(this).find('a').attr('href')
        }
    
        section.subtitles.push(subtitle);
      });
    
      sections.push(section);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 2013-06-08
      相关资源
      最近更新 更多