How to load Json data

here in this code i am trying to get the json value. I can get the key value, but I can not get the value of val.

How can i do this?

JQuery Code:

$.getJSON('data.json', function(data) { var items = []; $.each(data, function(key, val) { alert(key); alert(val); items.push('<option value="' + key + '">'+key+'</option>'); //items.push('<li id="' + key + '">' +key + '</li>'); }); $('#project-list').html(items.join('')); }); 

here is the json data

 { "trng-java": {"1":"5"}, "trng-jast": {"2":"5"}, "trng-caml": {"3":"4"}, "trng-linx": {"1":"5"} } 

When I run this, I get the key value, but the val value appears as an Object.

+4
source share
2 answers

the value is an array, which, like others, suggested using val[index] to get the values, but if you want it to be a string, use

  var valString = val.toString(); 

this will return 1.5, 2.5 ...

+2
source

Try to access: val[0]

  $.getJSON('data.json', function(data) { var items = []; $.each(data, function(key, val) { alert(key); alert(val[0]); items.push('<option value="' + key + '">'+key+'</option>'); //items.push('<li id="' + key + '">' +key + '</li>'); }); $('#project-list').html(items.join('')); }); 
0
source

Source: https://habr.com/ru/post/1494019/


All Articles