我试图最终将我的json数据显示在标签中。但是,当我在console.log中记录json数据时,只显示最后两个对象。当我将数据传递给标签时,只显示最后一个对象。在此先感谢您的帮助!
这是我的代码:
var json =
{
"Question:": " What is my name? ",
"Answer:": " James ",
"Question:": " What is my age? ",
"Answer:": " 31 "
};
for (var key in json)
{
if (json.hasOwnProperty(key))
{
console.log(key + " = " + json[key]);
}
}
var label = Ti.UI.createLabel({
text: key + json[key]
});
win3.add(label);
答案 0 :(得分:0)
您的问题与Titanium无关。在JavaScript词典中,您不能拥有两个具有不同值的相同键。为了证明你犯了哪些错误,我会改写你的第一行:
var json = {};
json["Question:"] = " What is my name? ";
json["Answer:"] = " James ";
// We are fine untill now.
json["Question:"] = " What is my age? ";
json["Answer:"] = " 31 ";
// Here you overwrote values for keys "Question:" and "Answer:" which were set above.
要解决您的问题,我会将您的json字典更改为字典数组:
var i, key, label;
var json = [
{
"Question:": " What is my name? ",
"Answer:": " James ",
},
{
"Question:": " What is my age? ",
"Answer:": " 31 "
}
];
for (i in json) {
for (key in json[i]) {
label = Ti.UI.createLabel({
text: key + json[i][key]
});
win3.add(label);
}
}
答案 1 :(得分:0)
你的json对象密钥是重复的,javascript不会抱怨这个,它只会用第二个值覆盖第一个键值