2016-07-08 57 views
-1

所以我需要得到下面的值:我有一个JSON对象,我需要从中取出一些值。我如何在JQuery中做到这一点?

  • 位置
  • 状态
  • abc_status
  • S_S
  • S_E
  • n_c
 

    { 
     "skills": [], 
     "languages": [], 
     "cal_strs": [{ 
      "test": null, 
      "primary_test": null 
     }], 
     "id": 123, 
     "my_id": 1346, 
     "username": "blahblah", 
     "full_name": "mr blah", 
     "email": "[email protected]", 
     "location": "boston", 
     "manager": "boss", 
     "status": 1, 
     "abc_status": "here", 
     "s_s": "2010-06-08T23:00:00Z", 
     "s_e": "2010-06-13T07:00:00Z", 
     "n_c": "2010-07-08T07:00:00Z", 
     "last_here": null, 
    } 

件事情我已经尝试:

数据[0] - 给我的左括号“{” 数据[“位置”] - 返回undefined

+1

? –

+0

我试图做访问对象数据[0]然而,这给了我的左括号'{' – edward

+0

我也尝试通过执行以下操作来访问对象属性:data ['location'] this undefined – edward

回答

3

你在这里的是一个对象字面,女巫可以被操纵无需使用jQuery的,读这个对象可以使用点符号基础上,重点 obj.key = value

var obj = 
    { 
     "skills": [], 
     "languages": [], 
     "cal_strs": [{ 
      "test": null, 
      "primary_test": null 
     }], 
     "id": 123, 
     "my_id": 1346, 
     "username": "blahblah", 
     "full_name": "mr blah", 
     "email": "[email protected]", 
     "location": "boston", 
     "manager": "boss", 
     "status": 1, 
     "abc_status": "here", 
     "s_s": "2010-06-08T23:00:00Z", 
     "s_e": "2010-06-13T07:00:00Z", 
     "n_c": "2010-07-08T07:00:00Z", 
     "last_here": null 
    } 
console.log(obj.location); 
console.log(obj.status); 

var abc_status = obj.abc_status;//save the value to a variable 
+0

答案中的代码显示的是使用对象字面值创建的对象。这是*不* JSON,这是用于数据交换的字符串格式。 – nnnnnn

+0

我能够从对象中获取值,即删除JSON.stringify(data)。感谢堆 – edward

+0

如果我需要从“cal_strs”:[{}]数组获得第二个值,那么我该怎么做? – edward

1

你试图访问您的JSON对象,就好像它是一个数组来获取对象的值。不是。你已经可以访问你的对象了,因为它已经是一个合适的javascript对象了(它不是json)。简单地说就是对象存储到一个变量(如var obj = {...}东西,然后键入obj.skills获得的技能阵列回来。如果你想从cal_strs阵列得到test,你可以做obj.cal_strs[0].test

0

使用下划线(_。摘去)获得从对象 或者试图定义一个新的变量,并重新分配它你尝试什么样的具体数值。

var s = { 
     "skills": [], 
     "languages": [], 
     "cal_strs": [{ 
      "test": null, 
      "primary_test": null 
     }], 
     "id": 123, 
     "my_id": 1346, 
     "username": "blahblah", 
     "full_name": "mr blah", 
     "email": "[email protected]", 
     "location": "boston", 
     "manager": "boss", 
     "status": 1, 
     "abc_status": "here", 
     "s_s": "2010-06-08T23:00:00Z", 
     "s_e": "2010-06-13T07:00:00Z", 
     "n_c": "2010-07-08T07:00:00Z", 
     "last_here": null, 
    } 
var t = {}; 
t['location'] = s.location; 
t['status'] = s.status; 
t['abc_status'] = s.abc_status; 
t['s_s'] = s.s_s; 
t['s_e'] = s.s_e; 
t['n_c'] = s.n_c; 

的情况下,多个阵列使用下划线。

+0

您不需要使用下划线从javascript对象获取值。这是本地的。没有库需要 – mwilson

+0

用于循环条件来获取数组值,并获得每个值。 @mwilson – Sathish

+0

这里不需要for循环,除非OP想循环js对象中的一个数组。我也会谨慎使用一个JavaScript对象的for循环,因为它可能是嵌套的,因此需要递归或其他逻辑。然而,你当然可以使用'for in'循环遍历这些对象。 – mwilson

相关问题