Reputation: 306
I was working on how to extract data from JSON data
I wrote the below code to extract the variable named code that is equal to ur
But not getting the results.
<script>
var txt = '{ "type":"ipv4", "location":{ "geoname_id":2816, "languages":[ { "code":"en", "name":"English" }, { "code":"ur", "name":"Urdu" } ], "is_eu":false } }';
var obj = JSON.parse(txt);
console.log(obj.location.languages.code);
</script>
Upvotes: 1
Views: 106
Reputation: 2566
languages
is an array, so try something like that:
obj.location.languages[0].code
Upvotes: 0
Reputation: 16756
obj.location.languages
is an Array, you cannot access code
property be requesting it directly on it. code
property of which item it should give you back after all, one of English or Urdu? You will need to use an index of the item (starts with 0) to access it, or use one of the iterator methods on the Array, like forEach()
, map()
or reduce()
to cycle trhough all of them. Here's an example:
var txt = '{ "type":"ipv4", "location":{ "geoname_id":2816, "languages":[ { "code":"en", "name":"English" }, { "code":"ur", "name":"Urdu" } ], "is_eu":false } }';
var obj = JSON.parse(txt);
var html = '';
obj.location.languages.forEach(function(lang) {
html += '<li>' + lang.name + ' (' + lang.code + ')</li>';
});
document.getElementById('languages').innerHTML = html;
Languages: <br />
<ul id="languages"></ul>
Upvotes: 1
Reputation: 1596
Below code will get you all language code as an array.
<script>
var txt = '{ "type":"ipv4", "location":{ "geoname_id":2816, "languages":[ {"code":"en", "name":"English" }, { "code":"ur", "name":"Urdu" } ], "is_eu":false } }';
var obj = JSON.parse(txt);
document.write(obj.location.languages.map((language,i)=>language.code));
</script>
Upvotes: 0
Reputation: 357
You must use index after languages propert. Because this propert type is array.
<script>
var txt = '{ "type":"ipv4", "location":{ "geoname_id":2816, "languages":[ { "code":"en", "name":"English" }, { "code":"ur", "name":"Urdu" } ], "is_eu":false } }';
var obj = JSON.parse(txt);
document.write(obj.location.languages[0].code);
</script>
Upvotes: 0