[英]Error in parsing the JSON response in JQuery, javascript
I am getting following as the JSON response but some indexes are having spaces like 'Employee Id'. 我将其作为JSON响应进行跟踪,但某些索引的空格类似“员工ID”。 That's why I am unable to parse it. 这就是为什么我无法解析它。 Can anyone suggest the way to parse it in JavaScript? 谁能建议用JavaScript解析的方式?
{
"Employees": [
{
"Employee": {
"Employee ID": "777",
"Short Name": "abc",
"First name": null,
"Middle name": null,
"Last name": null,
"Designation": "Senior Engineer",
"Ext-1": null,
"Ext-2": null,
"Mobile-1": null,
"Mobile-2": null,
"Email": "a.b@gmail.com"
}
},
{
"Employee": {
"Employee ID": "888",
"Short Name": "xyz",
"First name": null,
"Middle name": null,
"Last name": null,
"Designation": "Test Lead",
"Ext-1": null,
"Ext-2": null,
"Mobile-1": null,
"Mobile-2": null,
"Email": "c.d@gmail.com"
}
}
]
}
My code - 我的代码-
function GetContacts() {
$.ajax({
type: "GET",
contentType: 'application/json; charset=utf-8',
url: "http://. . . . . .",
dataType: "json",
success: function(data) {
//alert(data.getString("Employee ID"));
$.each(data, function(i, contactList) {
alert('First Loop' + i);
alert('First Loop' + contactList[0]);
$.each(contactList, function(j, Contact) {
//alert('Second Loop'+Contact);
var fnalObj = Contact;
//alert(fnalObj);
//alert(fnalObj.["Employee"]["Employee ID"]);
//alert(Employees[j]["Employee"]["Email"]);
//alert(Employees[0]["Employee"]["Employee ID"]);
alert(fnalObj.Employee.Email);
alert(fnalObj.Employee.Designation);
alert(fnalObj.Employee.Ext - 1);
alert(fnalObj.Employee.Mobile - 1);
});
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
}
});
}
Parsing is fine. 解析很好。
The problem is accessing the keys which are made of non-alhpanumeric characters.. like spaces, dashes etc.. 问题是访问由非字母数字字符组成的键,例如空格,破折号等。
These properties must be handled with the []
notation like this 这些属性必须使用[]
符号处理,如下所示
alert(fnalObj.Employee['Employee ID']);
alert(fnalObj.Employee['Ext-1']);
Demo at http://jsfiddle.net/h9sbn/ 演示在http://jsfiddle.net/h9sbn/
You cannot do fnalObj.Employee.Ext - 1
. 您不能执行fnalObj.Employee.Ext - 1
。 The correct way to do it would be fnalObj.Employee['Ext-1']
. 正确的方法是fnalObj.Employee['Ext-1']
。 Here is the jsFiddle http://jsfiddle.net/naryad/VNXa5/1/ 这是jsFiddle http://jsfiddle.net/naryad/VNXa5/1/
When using fnalObj.Employee.Ext - 1
, it gets resolved to undefined - 1
which in turn returns you NaN
使用fnalObj.Employee.Ext - 1
,它将解析为undefined - 1
,这反过来又会返回NaN
Same applies to fnalObj.Employee.Mobile - 1
同样适用于fnalObj.Employee.Mobile - 1
$.each(contactList, function(j, Contact) {
//alert('Second Loop'+Contact);
var fnalObj = Contact;
$.each(finalObj, function (key, value) {
var newKey = key.replace(/[\s]\-/g, '_');
delete finalObj[key];
finalObj[newKey] = value;
});
//revised alerts here.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.