Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I've got to the stage of fetching the page and sticking it in a div. I can use some jquery selectors to identify the data rows of the table im after.

However its old verbose html e.g.

  <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.

Whats the best way to scrape the important data ? I'd like it to ultimately reside in some JSON ? regex ? templates ???

like image 262
wmitchell Avatar asked Jun 30 '26 06:06

wmitchell


1 Answers

You'll have to do some recursing here, and apply selectors from each TR tag.

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.

like image 182
Steven de Salas Avatar answered Jul 01 '26 21:07

Steven de Salas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!