2017-02-22 84 views
0

我正在開發一個前端和後端分離的網站。我用jQuery來發送請求,得到的結果作爲一個JSON對象:如何使用jquery處理多個json對象

{ 
    "item": [ 

    ], 
    "shop": [ 

    ], 
    "user": [ 
    { 
     "user_id": "9", 
     "full_name": "Minh Duc", 
     "email": "[email protected]", 
     "fb_link": "https:\/\/www.facebook.com\/SieuNhan183", 
     "user_name": "Duc", 
     "password": "37cd769165eef9ba6ac6b4a0fdb7ef36", 
     "level": "0", 
     "admin": "0", 
     "dob": "1996-03-18", 
     "location": "Ho Chi Minh", 
     "user_image_url": null 
    } 
    ] 
} 

現在我找到一種方法,從對象用戶獲取數據。我怎樣才能做到這一點與JavaScript?

+0

$ jsonObject.user [0]將是你想要的用戶對象。使用 。 (點)來訪問你想要的對象屬性 –

+0

[沒有這樣的東西作爲「JSON對象」](http://benalman.com/news/2010/03/theres-no-such-thing-asa-a- JSON /) – Andreas

回答

2

當你有數據(例如它在data)使用點符號來獲取用戶的節點。

用戶是一個數組,因此使用[]來訪問單個元素,例如, [0]

var data = { 
 
    "item": [ 
 

 
    ], 
 
    "shop": [ 
 

 
    ], 
 
    "user": [ 
 
    { 
 
     "user_id": "9", 
 
     "full_name": "Minh Duc", 
 
     "email": "[email protected]", 
 
     "fb_link": "https:\/\/www.facebook.com\/SieuNhan183", 
 
     "user_name": "Duc", 
 
     "password": "37cd769165eef9ba6ac6b4a0fdb7ef36", 
 
     "level": "0", 
 
     "admin": "0", 
 
     "dob": "1996-03-18", 
 
     "location": "Ho Chi Minh", 
 
     "user_image_url": null 
 
    } 
 
    ] 
 
} 
 

 

 
console.log(data.user[0].user_id)

3

補充@arcs回答,請記住,在Javascript中,您可以訪問使用點符號(data.user[0].user_id)或方括號標記對象的成員。通過這種方式:

data['user'][0]['user_id'] 

這是有用的,因爲你可以有一個「類」數組,然後做這樣的事情:

['item', 'shop', 'user'].forEach((array) => processArray(data[array][0])); 

,那麼你只能篩選一些類或更高級的東西

0

我更喜歡用方括號這樣的:

$jsonObject["user"][0]["user_id"] 

,但你可以使用這樣的點:

data.user[0].user_id 

是一樣的東西。

如果你想檢查是否存在屬性,你可以做到這一點:

if(typeof $jsonObject["user"] !== 'undefined'){ 
    //do domethings as typeof $jsonObject["user"][0]["user_id"] 
} 

如果你想獲取屬性dinamically你可以做到這一點:

const strId = "id"; 
const strName = "name"; 

//get user_id 
let user_id = $jsonObject[user][0]["user_" + strId ]; 
//get user_name 
let user_name = $jsonObject[user][0]["user_" + strName]; 

但不是很漂亮。