解析没有子节点的JSON文档将返回undefined

时间:2012-10-29 15:58:01

标签: javascript json parsing

webservice在

下面返回此JSON
[
  {
"companyuserId": "2",
"name": "mike jones",
"superiorname": null,
"departmentId": "26",
"departmentname": "Design",
"companyId": "06",
"UDID": "8df912053a16ab2b4c66a",
"isActive": "1",
"devicetoken": "e8a4c1fad76b45d918f6745bfe60d32a81504",
"email": "mike@yahoo.co.uk",
"phone": "5456465465654"
  }
 ]

认为这将是直截了当的

            name = data.name;
            phone = data.phone;
            email = data.email;
            departmentname = data.departmentname;
            companyId = data.companyId;

但是我没有定义,我还能怎么做?我想也许数据可能是字符串格式,因为当我提醒数据时,我得到的结果是粘贴在上面而不是对象:对象

2 个答案:

答案 0 :(得分:2)

这是array of Objects ..对象是数组中的First item ..所以你需要使用索引来访问其中的对象..

而不是name = data.name;尝试此name = data[0].name;

            name = data[0].name;
            phone = data[0].phone;
            email = data[0].email;
            departmentname = data[0].departmentname;
            companyId = data[0].companyId;

答案 1 :(得分:1)

您的JSON对象是一个对象数组,因此必须使用完全限定名称进行访问。

试试这个:

name = data[0].name;
phone = data[0].phone;
email = data[0].email;
departmentname = data[0].departmentname;
companyId = data[0].companyId;