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

How to get the JSON object from the given code?

本文关键字:获取 JSON 对象 代码      更新时间:2023-09-26

我正在使用一个url,我的代码是:

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数据对象打印到一个警告框中。

将其分配给var以获得一个Object
如果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
}
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.');
});