this is might be a very basic question, but seems like it's not easy to find the answer. I have a Json, more or less is like:
languages = {
"aa":{"iso639-2T":"aar","family":"Afro-Asiatic","labels":{"language_names":["Afar"],"native_names":["Afaraf"]}},
"ab":{"iso639-2T":"abk","family":"Northwest Caucasian","labels":{"language_names":["Abkhaz"],"native_names":["\u0430\u04a7\u0441\u0443\u0430"]}},
"af":{"iso639-2T":"afr","family":"Indo-European","labels":{"language_names":["Afrikaans"],"native_names":["Afrikaans"]}}, etc...etc... }
if you see json above, there's several language object inside languages variable. and each language object has its own name as its identifier ("aa", "ab", "af")
so then, my question is, how to get those identifier ("aa", "ab", "af") if i want to list all of those language in html? eg. if i want to create like a combo box (<option value="aa">Afar</option><option value="ab">Abkhaz</option><option value="af">Afrikaans</option>
)
actually what i want to achieve is something like this (in php)
$sampleArray = Array("aa" => "Afar", "ab" => "Abkhaz", "af" => "Afrikaans"); foreach($sampleArray as $id => $value){ /* I can get the id from $id* / }
is there any solution similar like php syntax above for my json in java script?
ps. if you're wondering why i'm not using array - I'm just thinking it will easier to grab certain language object (im just do something like: languages["af"]
to get afrikaans language) rather than i should do: loop through the entire language object and check one-by-one if the id is what i want, and then return it. - you can give me another suggestion for this if you guys have a better idea :)
Best Regards,
AnD
A JSONObject has few important methods to display the values of different types like getString() method to get the string associated with a key string, getInt() method to get the int value associated with a key, getDouble() method to get the double value associated with a key and getBoolean() method to get the boolean ...
Declare a JSON object and store it into variable. Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it.
this should do what you want..
to see them
for (var lang in languages)
alert(lang + ' : ' + languages[lang].labels.language_names[0]);
to put them in the DOM
var $select = $('selector to your select element');
for (var lang in languages)
$select.append('<option value="'+lang+'">' + languages[lang].labels.language_names[0] + '</option>');
Working code at http://www.jsfiddle.net/EsJAh/
You can use the "for"
for (var key in languages)
{
alert(key);
}
Did you try:
languages['af'].labels.language_names[0]
It will return Afrikaans
var data = new Array();
for(var lang in languages) {
data[lang] = languages[lang];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With