如何解析字符串的JSON对象 [英] How to parse a JSON object for a string
本文介绍了如何解析字符串的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JSON对象
{
"data": [{
"user_id":"1",
"user_name":"test",
"user_phone":"2147483647",
"user_email":"test@example.com"
}]
}
和jQuery循环功能
and a jQuery loop function
$.each(responseData, function(index, ProfileData) {
profiles.push(
application.getModel("Profile", [ ProfileData.user_id, ProfileData.user_name, ProfileData.user_phone, ProfileData.user_email ] )
);
});
但是当JSON对象变成这个时
But when the JSON object becomes this
{
"data": [{
"firm_id":"1",
"firm_name":"Firm",
"firm_phone":"2147483647",
"firm_email":"testfirm@example.com"
}]
}
然后我要检查JSON数据是否具有user
或firm
扩展名,并且还需要在push()
中使用它.
Then I want to check whether the JSON data has user
or firm
extensions, and also need to use this in the push()
instead.
application.getModel( "Profile", [ ProfileData.user_id, ProfileData.user_name, ProfileData.user_phone, ProfileData.user_email ] )
推荐答案
您可以像这样检查对象内部是否存在属性:
You can check for the existence of a property inside an object like so:
if('user_id' in ProfileData)
所以您的解决方案可能看起来像这样:
So your solution might look like this:
$.each(responseData, function(index, ProfileData) {
if('user_id' in ProfileData) {
profiles.push(
application.getModel("Profile", [ ProfileData.user_id, ProfileData.user_name, ProfileData.user_phone, ProfileData.user_email ] );
);
} else {
profiles.push(
application.getModel("Profile", [ ProfileData.firm_id, ProfileData.firm_name, ProfileData.firm_phone, ProfileData.firm_email ] );
);
}
});
另一种方法是合并不同的属性,并使用定义的任意一种:
Another approach would be to coalesce the different properties, and use whichever one is defined:
$.each(responseData, function(index, ProfileData) {
profiles.push(
application.getModel("Profile", [
ProfileData.user_id || ProfileData.firm_id,
ProfileData.user_name || ProfileData.firm_name,
ProfileData.user_phone || ProfileData.firm_phone,
ProfileData.user_email || ProfileData.firm_email
] );
);
});
这篇关于如何解析字符串的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文