Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  134] [ 3]  / answers: 1 / hits: 17495  / 9 Years ago, sat, december 26, 2015, 12:00:00

How can I get only the name from JSON file. Also code is perfectly working for getting the data from file.json i.e. that's not the problem for sure.



JavaScript:



var data = [];
function getName() {
//what should I write here to get only name from the first object i.e. John
//with this: data[0].name I am getting error!
}

var xhttp;
if(window.XMLHttpRequest)
xhttp = new XMLHttpRequest();
else
xhttp = new ActiveXObject(Microsoft.XMLHTTP);

xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4) {
data = JSON.parse(xhttp.responseText);
getName();
}
}

xhttp.open(GET,file.json,true);
xhttp.send();





file.json - JSON:



[
{
name:John,
city:London
},
{
name:Maria,
city:Rome
}
]




More From » arrays

 Answers
6

Pass the variable data through the function



var data = [];
function getName(data) {
return data[0].name;
}

var xhttp;
if(window.XMLHttpRequest)
xhttp = new XMLHttpRequest();
else
xhttp = new ActiveXObject(Microsoft.XMLHTTP);

xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4) {
data = JSON.parse(xhttp.responseText);
getName(data);
}
}

xhttp.open(GET,file.json,true);
xhttp.send();


Also, if you want to retrieve all names, you can do something like this :



function getName(data) {
var names = [];
for (var i = 0; i < data.length; i++) {
names.push(data[i].name);
}
return names;
}


(The data is the array data)


[#63937] Wednesday, December 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anniejulietteb

Total Points: 740
Total Questions: 125
Total Answers: 97

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
anniejulietteb questions
;