Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery HTML to JSON, including href attribute

Tags:

json

html

jquery

I have data in markup like this:

  <p class="bbook">Lorem</p>
  <p class="bref">
     <a class="ref" href="prin.v.ii.ii.html">2:15</a>
     <a class="ref" href="prin.v.i.v.html">3:17-19</a>
     <a class="ref" href="prin.v.v.html">3:19 </a>
  </p>

 <p class="bbook">Ipsum</p>
 <p class="bref">
     <a class="ref" href="sec.vii.xxii.html">10:18</a>
     <a class="ref" href="sec.vii.ix.html">10:27</a>
     <a class="ref" href="sec.vii.xxiii.html">10:28</a>
 </p>

I'd like to convert it to a JSON object like this:

{
    "Lorem": {
        "prin.v.ii.ii.html": "2:15",
        "prin.v.i.v.html": "3:17-19",
        "prin.v.v.html": "3:19"
    },
    "Ipsum": {
        "sec.vii.xxii.html": "10:18",
        "sec.vii.ix.html": "10:27",
        "sec.vii.xxiii.html": "10:28"
    }
}

I've seen some HTML to JSON solutions here but none that I can find that deal with attributes. I know it might be easier if the markup had ul's but it doesn't. How could I convert this?

like image 382
nathanbweb Avatar asked Jun 14 '26 10:06

nathanbweb


2 Answers

Pretty easily, I should think. Here's some example code in jQuery-flavored Javascript, but you can adjust to taste with the DOM traverser and JSON library in your language of choice. (For example, in Perl, you'd use the HTML::TreeBuilder and JSON modules.)

var json_obj = {};
$('p.bbook').each(function(i,el) {
    var which = $(el).text();
    var refs = {};
    $(el).next('p.bref').find('a.ref').each(function(i,el) {
        var href = $(el).attr('href');
        var chapter_verse = $(el).text();
        refs[href] = chapter_verse;
    });
    json_obj[which] = refs;
});
var json_result = JSON.stringify(json_obj);

At this point, json_result contains a JSON string whose contents match what you describe in your question.

like image 134
Aaron Miller Avatar answered Jun 18 '26 01:06

Aaron Miller


Use $.parseJSON() and $.each() from the jQuery framework. Here an exemple :

$(document).ready(function () {
    var jsonp = '[{"Lang":"jQuery","ID":"1"},{"Lang":"C#","ID":"2"}]';
    var lang = '';
    var obj = $.parseJSON(jsonp);
    $.each(obj, function () {
        lang += this['Lang'] + "<br/>";
    });
    $('span').html(lang);
});​

like image 23
jody_lognoul Avatar answered Jun 18 '26 01:06

jody_lognoul



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!