Search code examples
javascriptjsontitanium

Why is only part of my json data being logged?


I am trying to eventually have my json data displayed in a label. However, when I console.log the json data, only the last two objects are displayed. When I pass the data to a label, only the last object is displayed. Thanks in advance for any help!

Here is my code:

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);

Solution

  • Your issue has nothing to do with Titanium. In JavaScript dictionary you can't have two same keys with different values. To demonstrate where you made mistake, I'll rewrite your first lines:

    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.
    

    To fix your problem, I'd change your json dictionary into array of dictionaries:

    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);
        }
    }