1

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>
J. Doe
  • 306
  • 2
  • 12
  • it works. Maybe you cant see result. Try with console.log() – Emircan Ok Feb 08 '19 at 14:46
  • 1
    Its not working bro, want to get code from the json data. – J. Doe Feb 08 '19 at 14:48
  • Don't use `document.write`. This is working correctly. –  Feb 08 '19 at 14:50
  • 1
    Possible duplicate of [document.write clears page](https://stackoverflow.com/questions/10873942/document-write-clears-page) –  Feb 08 '19 at 14:51
  • 1
    Your `languages` is an Array, you have to use an index to access it first and then the prop name like `code` for example `obj.location.languages[0].code` – danillouz Feb 08 '19 at 14:51

4 Answers4

1

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>
jayarjo
  • 16,124
  • 24
  • 94
  • 138
0

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>
Emircan Ok
  • 320
  • 2
  • 13
0

languages is an array, so try something like that:

obj.location.languages[0].code
veben
  • 19,637
  • 14
  • 60
  • 80
Haris Bouchlis
  • 2,366
  • 1
  • 20
  • 35
0

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>
Bipul
  • 1,564
  • 1
  • 15
  • 16