2017-06-22 23 views
0

retrive我收到以下JSON作爲響應如何檢查,然後只從JSON

{ 
       "user_details": [ 
       { 
         "Name": "Mark" 
       }, 
       { 
         "Age": "35" 
       }, 
       { 
         "Gender": "Male" 
       }, 
       { 
         "Country": "US" 
       }] 
} 

我解析此JSON如下圖所示

var ajaxresponse = response.user_details; 
     if (ajaxresponse.length > 0) 
     { 
       var Name = ajaxresponse[0].Name; 
       var Age = ajaxresponse[1].Age; 
       var Gender = ajaxresponse[2].Gender; 
       var Country = ajaxresponse[3].Country; 
       console.log(Name); 
     } 

這是工作的罰款。

我的問題是,如果密鑰的任何一個在JSON失蹤例如「名稱」缺少,它打破和我越來越不確定

是否可以檢查是否存在,然後回顧?

https://jsfiddle.net/o2gxgz9r/9078/

對於答案我修改我的JSON來

{ 
       "user_details": [ 
       { 
        "Name": "Mark", 
         "Age": "35", 
         "Gender": "Male", 
         "Country": "US" 
         } 
       ] 
     } 

但hasOwnProperty不工作?

請參閱本小提琴

https://jsfiddle.net/o2gxgz9r/9085/

+0

也許[這回答你的問題](https://stackoverflow.com/questions/20804163/check-if-a-key-exists-inside-a-json-object) –

+0

你需要重構該JSON。 'user_details'內的數組是不必要的,並且不可能預測給定字段名稱的數組索引(如果缺少「名稱」,則所有其他字段都會向下移動。)只需製作一個普通的舊對象即可。 –

+0

重新更新:更好,但數組仍然是不必要的!只需使用一個普通的對象,比如''user_details「:{」Name「:」Mark「,」Age「:」35「} –

回答

2

首先,這是一個錯誤的方式發送數據作爲respo無論它來自何方,都是如此。

理想的方法應該是一個對象映射或載體下面給出:

user_details: { 
    name: "Mark", 
    age: 35, 
    gender: "male", 
    country: "USA" 
} 

其次,如果要爲你所得到的數據結構的溶液中,你將不得不實際穿過每個陣列項目,看看是否存在一個屬性。

var arr = ajaxResponse; 

var name,age,country,age; 

arr.forEach(function(item){ 
    if(item.hasOwnProperty('name')){ 
     name = item.name 
    } 
    //similarly for other objects in the array 
)); 
+0

我改變了我的JSON結構,但是爲什麼hasOwnProperty不工作?https:// jsfiddle。 net/o2gxgz9r/9084/ – Pawan

+0

檢查此工作小提琴https:// jsfiddle。net/ej4z21nf/ –

+0

你正在使用一個數組,而你應該使用一個對象。如果多個用戶的數據即將到來,則應使用對象數組。 –

0

使用JavaScript的hasOwnProperty功能,

if(json_object.hasOwnProperty('name')){ 
//do struff 
} 

這裏

if (ajaxresponse.length > 0) 
    { 
     if(ajaxresponse.hasOwnProperty("Name")) 
     { 
      var Name = ajaxresponse[0].Name; 
      var Age = ajaxresponse[1].Age; 
      var Gender = ajaxresponse[2].Gender; 
      var Country = ajaxresponse[3].Country; 
      console.log(Name); 
     } 
    } 
0

讓它多一點一般嘗試這樣的事情,這將通過爲每個項目user_details陣列設置屬性迭代。

var ajaxresponse = response.user_details; 
var user_details = ajaxresponse.reduce(function(details, detail){ 
    // details is the object we'll populate and will get assigned to user_details 
    // detail is the current user detail object - Name/Age/Gender/Country 

    // get property name for this "detail" 
    var propertyName = Object.getOwnPropertyNames(detail)[0]; 

    // set the property and value for the current detail object 
    details[propertyName] = detail[propertyName]; 

    // return the updated details object for the next iteration 
    return details; 
}, {}); 

console.log(user_details.Name); 

這有額外的好處,結果集中的任何新屬性將自動處理。

相關問題