Reputation: 177
I am trying to get json data from url. Here's the js
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'URL that has JSON format');
myRequest.onload = function() {
var myData = JSON.parse(myRequest.responseText);
console.log(myData);
};
myRequest.send();
The JSON data format is like this
"ING":
[
{
"#":1,
"Team":"Manchester City",
"Main":37,
"Poin":97
},
{
"#":2,
"Team":"Manchester United",
"Main":37,
"Poin":78
},
{
"#":3,
"Team":"Tottenham Hotspur",
"Main":37,
"Poin":74
},
{
"#":4,
"Team":"Liverpool",
"Main":37,
"Poin":72
},
{
"#":5,
"Team":"Chelsea",
"Main":37,
"Poin":70
}
]
}
for example i want to fetch Chealsea. How can i achieve that? i know that i have to change
console.log(myData);
What should i do? Thanks
Upvotes: 0
Views: 97
Reputation: 27192
Try this :
var myData = {
"ING": [{
"#": 1,
"Team": "Manchester City",
"Main": 37,
"Poin": 97
},
{
"#": 2,
"Team": "Manchester United",
"Main": 37,
"Poin": 78
},
{
"#": 3,
"Team": "Tottenham Hotspur",
"Main": 37,
"Poin": 74
},
{
"#": 4,
"Team": "Liverpool",
"Main": 37,
"Poin": 72
},
{
"#": 5,
"Team": "Chelsea",
"Main": 37,
"Poin": 70
}
]
};
var res = myData.ING.filter(obj => obj.Team == "Chelsea");
console.log(res[0].Team);
Upvotes: 0
Reputation: 1204
To read a JSON. Notice the bracket type,
if it has [], then treat that part as an array, if it has curly braces {3, then as an object.
to access Array object, use index, like 0, 1, 2 ...
to access objects, you can use dot notation your_object.key
oryour_object["key"]
in your case, we can read it like
let json = {"ING":[{...}]}
json["ING"][0]["SOME_KEY"] ...
Upvotes: 1
Reputation: 73241
You can use find()
to find something in an array. I changed Chelsea with Liverpool, as they will win the Champions League this year. Who cares about another team then...
let obj = {"ING":
[
{
"#":1,
"Team":"Manchester City",
"Main":37,
"Poin":97
},
{
"#":2,
"Team":"Manchester United",
"Main":37,
"Poin":78
},
{
"#":3,
"Team":"Tottenham Hotspur",
"Main":37,
"Poin":74
},
{
"#":4,
"Team":"Liverpool",
"Main":37,
"Poin":72
},
{
"#":5,
"Team":"Chelsea",
"Main":37,
"Poin":70
}
]
}
console.log(obj.ING.find(e => e.Team === 'Liverpool'));
Upvotes: 1
Reputation: 4942
You can use callback, promises or async/await. Here's a way that you can use callback to get and use the retrieved data:
function getUrl(url, callback) {
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url);
myRequest.onload = function() {
var myData = JSON.parse(myRequest.responseText);
console.log(myData);
callback(myData);
};
myRequest.send();
}
and you request and use your data like so:
getUrl('URL for JSON DATA', function(data) {
// find chealsea
var chealsea = data.ING.find(function(entry) { return entry.Team === 'Chealsea' });
console.log(chealsea);
});
Upvotes: 1