简体   繁体   English

从旧的html dom元素创建json

[英]creating json from old html dom element

I doing a little jquery+greasemonkey which I'm trying to use to redo an interface of an internal work site I have to use every day to try and make it a little more usable. 我正在做一个小jquery + greasemonkey,我试图用它来重做一个内部工作站点的界面,我每天都要使用它来尝试让它更有用。

I've got to the stage of fetching the page and sticking it in a div. 我已经到了获取页面并将其粘贴在div中的阶段。 I can use some jquery selectors to identify the data rows of the table im after. 我可以使用一些jquery选择器来识别表后面的数据行。

However its old verbose html eg 然而它的旧verbose html例如

  <tr style="font-family:blaaa">
     <td>1.</td>
     <td><a target="_BLANK" href="url=my bugs">13312800</a></td>
     <td sorttable_customkey="20110512">
       12-MAY-11
     </td>
     <td> Many more tds </td>
 </tr>

I have another tr which has the info i might at one stage like to use as the keys in my json. 我有另一个tr,它有一个阶段的信息,可以用作我的json中的键。

Whats the best way to scrape the important data ? 什么是刮掉重要数据的最佳方法? I'd like it to ultimately reside in some JSON ? 我希望它最终存在于一些JSON中? regex ? 正则表达式? templates ??? 模板???

You'll have to do some recursing here, and apply selectors from each TR tag. 你必须在这里做一些递归,并从每个TR标签应用选择器。

var recordset = [];
$('table.myTable tr').each(function(i,e) {
    var record = {
       id: $(e).find('td:nthchild(2) a').text(),
       url: $(e).find('td:nthchild(2) a').attr('href'), 
       date: $(e).find('td:nthchild(3)').text(), 
       comment: $(e).find('td:nthchild(4)').text()
    };
    recordset.push(record);
});

// Here you have complete recorset:
console.log(recordset);

// To output some JSON in a string
for (var i = 0; i < recordset.length; i ++) {
   alert($.param(recordset[i]));
}

If you'd like to output this data using specific DOM try using jQuery templates , particularly {{each}} tags for rendering lists of items, I found them quite easy to use and very flexible for rendering JSON data. 如果你想使用特定的DOM输出这些数据,请尝试使用jQuery模板 ,特别是{{each}}标签来呈现项目列表,我发现它们非常易于使用,并且非常灵活地呈现JSON数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM