如何从给定的代码中获取JSON对象?

时间:2015-03-19 09:56:55

标签: javascript json

我使用的是我的代码:

var url="http://nucleus/api/projectlist?format=json" 
var json=JSON.parse(this.responseText);

浏览器中的JSON格式数据如下所示

{
    "1": {
        "id": "91",
        "title": "Nucleus Aura",
        "project_locations": "TVm, Kochi",
        "project_type": "Villa",
        "project_status": "Book Now",
        "count_plan": 0,
        "image": "uploads/project_images/projects_images_image1415954647.png",
        "imagetitle": "Villa Night"
    }
}

我想将JSON数据对象打印到警告框。

2 个答案:

答案 0 :(得分:0)

将其分配给var以获取对象 如果responseText为

{
    "one": {
        "id": "91",
        "title": "Nucleus Aura",
        "project_locations": "TVm, Kochi",
        "project_type": "Villa",
        "project_status": "Book Now",
        "count_plan": 0,
        "image": "uploads/project_images/projects_images_image1415954647.png",
        "imagetitle": "Villa Night"
    }
}

然后,

getJSON(url, function(json){
    alert(json);// will give output like [object][Object]
    alert(json.one.id);// will give output 91
}

答案 1 :(得分:0)

var getJSON = function(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
      } else {
        reject(status);
      }
    };
    xhr.send();
  });
};

var url = "http://nucleus/api/projectlist?format=json";
getJSON(url).then(function(data) {
alert('Your Json result is:  ' + data.result); //you can comment this, i used it to debug

    result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});