我尝试根据我在网上看到的例子动态构建json结构对象,但没有成功。 这是我试图构建的json:
{
"campaigns": [
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
},
{
"campaign_id":,
"profile_id":,
"state":,
"goal":
}
]
}
这是代码: 每次有数据构建广告系列(在json中)元素时都会调用此函数
var campaignsJson ={};
campaignsJson.campaigns =[];
var i = 0;
function buildJson(stateCampaignId,
profile_id,
stateSelectedValue,
dailyImpressionGoalValue,
pacingValue,
segmentGroupTargetsUpdatedataValue,
frequencytypeProfileValue,
frequencysetProfileValue
)
{
campaignsJson.campaigns[i].campaign_id = stateCampaignId;
campaignsJson.campaigns[i].profile_id = profile_id;
campaignsJson.campaigns[i].state = stateSelectedValue;
campaignsJson.campaigns[i].goal = dailyImpressionGoalValue;
i++;
var campaignsJsonstringify = JSON.stringify(campaignsJson);
alert(campaignsJsonstringify);
}
它给了我“无法设置未定义的属性campaign_id” 这意味着什么?为什么?
答案 0 :(得分:4)
就在
之前campaignsJson.campaigns[i].campaign_id = stateCampaignId;
添加:
campaignsJson.campaigns[i] = {};
因此,您可以在其上设置属性。
现在,请不要谈论“JSON结构”。你构建的是一个普通的标准JavaScript对象,而JSON只是基于字符串的交换格式。