首页 > 解决方案 > 如何遍历 HTML 元素并填充 Json 对象?

问题描述

我正在遍历 html 文件中的所有 html 标签,检查这些标签是否匹配条件,并尝试组成以下模式的 JSON 对象:

[
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  },
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  },
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  }
]

但我只想为元素创建新条目,分类为“标题”,所有其他元素都必须添加到之前创建的条目中。我如何做到这一点?

当前代码:

$('*').each((index, element) => {


  if ( $(element).hasClass( "header" ) ) {
      jsonObject.push({
          title: $(element).text()
      });
  };
  if( $(element).hasClass( "date" )) {
      jsonObject.push({
          date: $(element).text()
      });
   }

   //links.push($(element))
});
console.log(jsonObject)

结果是:

  {
    title: 'TestA'
  },
  { date: '10.10.10' },
  {
    title: 'TestB'
  },
  { date: '10.10.11' }

我希望它在这个阶段是这样的:

      {
        title: 'TestA'
      ,
       date: '10.10.10' },
      {
        title: 'TestB'
      ,
       date: '10.10.11' }

UPD: 这是 HTML 文件的示例:

<h1 class="header">H1_Header</h1>
<h2 class="date">Date</h2>
<p>A.</p>
<p>B.</p>
<p>С.</p>
<p>D.</p>
<a class="source"><a href="http://">http://</a></a>
<h1 class="header">H1_Header2</h1>
<h2 class="date">Date2</h2>
<p>A2.</p>
<p>B2.</p>
<p>С2.</p>
<p>D2.</p>
<a class="source"><a href="http://2">http://2</a></a>

感谢您的时间!

标签: javascripthtmljquerycheerio

解决方案


根据您的示例Html,您尝试收集的所有内容似乎都是线性顺序,因此您会得到一个标题、日期、正文和链接,然后是一个包含您要收集的相关项目的新标题,因为这似乎没有以非线性方式订购东西的复杂性,您可以执行以下操作:

let jsonObject = null;
let newObject = false;
let appendParagraph = false;
let jObjects = [];

$('*').each((index, element) => {
  if ($(element).hasClass("header")) {
      //If newObject is true, push object into array
      if(newObject)
         jObjects.push(jsonObject);
      //Reset the json object variable to an empty object
      jsonObject = {};
      //Reset the paragraph append boolean
      appendParagraph  = false;
      //Set the header property
      jsonObject.header = $(element).text();
      //Set the boolean so on the next encounter of header tag the jsobObject is pushed into the array
      newObject = true;
  };

  if( $(element).hasClass( "date" )) {
      jsonObject.date = $(element).text();
  }

  if( $(element).prop("tagName") === "P") {
      //If you are storing paragraph as one string value
      //Otherwise switch the body var to an array and push instead of append
      if(!appendParagraph){ //Use boolean to know if this is the first p element of object
         jsonObject.body = $(element).text();
         appendParagraph = true; //Set boolean to true to append on next p and subsequent p elements
      } else {
         jsonObject.body += (", " + $(element).text()); //append to the body
      }

  }

  //Add the href property
  if( $(element).hasClass("source")) {
       //edit to do what you wanted here, based on your comment:
       jsonObject.link = $(element).next().html(); 
       //jsonObject.href= $(element).attr('href');
  }
});

//Push final object into array
jObjects.push(jsonObject);

console.log(jObjects);

这是一个 jsfiddle:https ://jsfiddle.net/Lyojx85e/

我无法在小提琴上获取锚标签的文本(我相信因为嵌套的锚标签无效,浏览器会将其解析为单独的锚标签),但提供的代码应该可以在真实世界的示例中使用。如果.text()不起作用,您可以将其切换到.html()链接上,我对您尝试在此链接上获得的内容感到困惑,因此我更新了答案以获取链接的 href 属性,因为它看起来就是您想要的。问题是该类的锚没有 href 属性,所以我将把它留给您自己修复该部分,但这个答案应该可以满足您的需求。


推荐阅读