Search code examples
javascriptjqueryhtmljsonxml-to-json

Converting XML to JSON and output to HTML with jQuery


I'm trying to test out an idea I had but using this XML to JSON script: https://github.com/sergeyt/jQuery-xml2json

But then take the JSON data and then output that into HTML with jQuery.

So far, I've been able to load up the data correctly and I can console.log out the JSON data which turns out to be something like this:

releases:
  $: {}
  matching_count: "698"
  returned_count: "50"
  latestModified: "1537876805"
  release: Array(50)
   0:
    $: {}
    id: "713"
    headline: "Eiger BioPharmaceuticals to Participate in Investor Conferences"
    released: "1537876800"
    releaseDate: "Tue, 25 Sep 2018 08:00:00 -0400"
    modified: "1537876805"
    modifiedDate: "Tue, 25 Sep 2018 08:00:05 -0400"
  1:
   $: {}
    id: "712"
    headline: "Communications industry innovator to speak at AMEC Global Summit"
    released: "1491400800"
    releaseDate: "Wed, 05 Apr 2017 10:00:00 -0400"
    modified: "1491400806"
    modifiedDate: "Wed, 05 Apr 2017 10:00:06 -0400"
...

My JS code that I have so far is this:

var ul = $("<ul>").appendTo("body");
$.ajax({
  url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/8689/list.xml",
  dataType: "xml",
  success: function(response) {
    json = $.xml2json(response);
    console.log(json);
    $(json).each(function(index, headline) {
      ul.append($(document.createElement("li")).text(headline));
    });
  }
});

The issue is that when it renders out, all that comes back is [object Object] in a single li.

So, I know that I'm doing something incorrectly, but I'm not sure where and at what point I need to change over to get the data so I can render out the headline, releaseDate, and so on.

I've created a Codepen here: https://codepen.io/ultraloveninja/pen/YzPRjRw

I've read that I might need to use jQuery.parseJSON but after testing that a bit, I get some errors since it's still getting in that object.Object again.

I feel that I need to drill down a bit more to get within the releases.release somehow since that's where all the data is at to be rendered out.


Solution

  • The response you try to loop is an object representing the xml document. To access the releases array you have to use json["#document"].releases.release

    var ul = $("<ul>").appendTo("body");
    $.ajax({
      url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/8689/list.xml",
      dataType: "xml",
      success: function(response) {
        json = $.xml2json(response);
        let release = json["#document"].releases.release
        $(release).each(function(index, headline) {
          ul.append($(document.createElement("li")).text(headline.headline));
        });
      }
    });
    

    Example