使用jQuery将JSON feed解析为HTML

时间:2015-01-15 16:03:55

标签: jquery json parsing

我正在尝试将以下JSON Feed解析为HTML,但没有得到任何结果。

{
  @name: "App name",
  license: [
    {
      @name: "Apache License 2.0",
      component: [
        {
          name: "Product 1",
          url: "http://www.url.com"
        }, {
          name: "Product 2",
          url: "http://www.url.com"
        }, {
          name: "Product 3",
          url: "http://www.url.com"
        }
      ],
      licensetext: " license text here"
    }
  ],
  isProjectComplete: "true"
}

使用这个jQuery:

$.getJSON("https://json-feed-url.json", function (data) {
  var jsondata = json;
  var output = "<ul>";
  for (var i in jsondata.events) {
    output += "<li>" 
      + jsondata.component[i].name + " " 
      + jsondata.component[i].url + "--"
      + jsondata.license[i].licensetext
      + "</li>";
  }

  output += "</ul>";
  document.getElementById("content").innerHTML = output;
});

到这个div

<div id="content"></div>

不确定为什么它没有正确解析。这是jsFiddle

2 个答案:

答案 0 :(得分:0)

您有几个错误,从您发布的无效JSON开始。已更正它应该可以正常显示HERE及以下内容:

var yourJson = {
    "@name": "App name",
        "license": [{"@name": "Apache License 2.0",
            "component": [{
            "name": "Product 1",
                "url": "http://www.url.com"
        }, {
            "name": "Product 2",
                "url": "http://www.url.com"
        }, {
            "name": "Product 3",
                "url": "http://www.url.com"
        }],
            "licensetext": " license text here"
    }],
        "isProjectComplete": "true"
};

function convertJson(data) {
    var jsondata = data;
    var output = "<ul>";
    for (var i in jsondata.license[0].component) {
        output += "<li>" + jsondata.license[0].component[i].name + " " + jsondata.license[0].component[i].url + "--" + jsondata.license[0].licensetext + "</li>";
    }

    output += "</ul>";
    document.getElementById("content").innerHTML = output;
};

convertJson(yourJson);

您应该更加小心,并且应该学会更有效地使用调试工具。

答案 1 :(得分:0)

你在jsFiddle中输错了

// WRONG
$.getJSON("http://jsonurl.json";, function (data) {
// CORRECT
$.getJSON("http://jsonurl.json", function (data) {