如何解析字符串的JSON对象

时间:2011-12-14 10:15:37

标签: jquery json

我有一个JSON对象

{
    "data": [{
        "user_id":"1",
        "user_name":"test",
        "user_phone":"2147483647",
        "user_email":"test@example.com"
    }]
}

和jQuery循环函数

$.each(responseData, function(index, ProfileData) {
    profiles.push(
        application.getModel("Profile", [ ProfileData.user_id, ProfileData.user_name, ProfileData.user_phone, ProfileData.user_email ] )
    );
});

但是当JSON对象变成这个

{
    "data": [{
        "firm_id":"1",
        "firm_name":"Firm",
        "firm_phone":"2147483647",
        "firm_email":"testfirm@example.com"
    }]
}

然后我想检查JSON数据是否包含userfirm个扩展名,并且还需要在push()中使用它。

application.getModel( "Profile", [ ProfileData.user_id, ProfileData.user_name, ProfileData.user_phone, ProfileData.user_email ] )

3 个答案:

答案 0 :(得分:1)

您可以检查对象内是否存在属性,如下所示:

if('user_id' in ProfileData)

所以你的解决方案可能如下所示:

$.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 ] );
        );
     }
});

另一种方法是合并不同的属性,并使用定义的任何属性:

$.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
        ] );
    );
});

答案 1 :(得分:0)

我认为组织json数据的方式存在问题。您可能需要在json中拆分用户和公司。但是,如果您无法控制json的格式,您可以在处理之前检查数据对象中是否包含某些数据,例如“user_id”。

答案 2 :(得分:0)

这将是我的方式。

var responseData = {
    "data": [{
        "user_id": "1",
        "user_name": "test",
        "user_phone": "2147483647",
        "user_email": "test@example.com"}]
};

$.each(responseData.data, function(index, dataRow) {
    var getModelDataArray = [];

    $.each(dataRow, function(key, profileData){
        getModelDataArray.push(profileData);
    });

    profiles.push(application.getModel("Profile", getModelDataArray));
});

为了能够使用此方法,您需要知道可以从服务器获得哪些数据。否则,您最终可能会使用不正确的getModelDataArray来使用getModel()。这段代码可以在小提琴here中找到。

相关问题