2017-02-22 86 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]; 

但不是很漂亮。