Really stuck with a loop of data inside a json result - javascript

Recently posted about looking through some json output from an API and got pointed to $getJSON and for loop issue
But im still really struggling and nothing I do works.
I have the following output from an API call :
{
"about": {
"name": "API",
"version": "2018.1.25.1",
"method": "get"
},
"sessions": {
"0": {
"sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
"id": "121667",
"geolat": "51.9125118",
"geolon": "-2.1210269"
},
"1": {
"sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
"id": "122589",
"chatstarted": "2018-02-24 23:41:51",
"geolat": "51.9125118",
"geolon": "-2.1210269"
}
},
"rescode": "200",
"executed": "nokeyfound-",
"queries": "5"
}
I just cant get it to loop through the "sessions" part of the Json.
The below "sort of works" but doesnt work at all, no errors, no output when loading it using $.getJSON (rather than just manually creating the object)
$.getJSON('https://api.php', function (Json) {
for (i in Json.sessions) {
alert(Json.sessions[i].id);
}
Surely it can't be that hard to just loop through only part of the data returned (the sessions) part.
What on earth am I doing wrong with this loop?
I just want to output sessionid on both rows. Seems impossible and been at this now for 9 hours straight no luck,
There has to be a way to just look at the sessions part and loop through the bits of that? surely? (0, 1 ,2 ,3 etc.. )
P.S I'm new to Javascript and JSON in particular and this is driving me insane.

Your result is not valid JSON because of a trailing , here:
"method": "get",
Always verify that the results you get back from a JSON request is valid before doing anything else.
Next, your syntax in the success handler is incorrect. You are missing a closing } for the for loop:
$.getJSON('https://api.php', function (Json) {
for (i in Json.sessions) {
alert(Json.sessions[i].id);
} // <-- You don't have this.
}
But, if we correct those things, then here's how we can iterate the results (keeping in mind that sessions is a key in the main object, but contains another object as its data:
var result = `{
"about": {
"name": "API",
"version": "2018.1.25.1",
"method": "get"
},
"sessions": {
"0": {
"sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
"id": "121667",
"geolat": "51.9125118",
"geolon": "-2.1210269"
},
"1": {
"sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
"cid": "122589",
"chatstarted": "2018-02-24 23:41:51",
"geolat": "51.9125118",
"geolon": "-2.1210269"
}
},
"rescode": "200",
"executed": "nokeyfound-",
"queries": "5"
}`;
resultObj = JSON.parse(result);
// Loop over the top-level object
for(var key in resultObj){
// Check the object key for the one we care about
if(key === "sessions"){
// Loop over the object stored in that key
for(var subKey in resultObj[key]){
// Access the sub-keys with an extra index:
console.log(resultObj[key][subKey]);
}
}
}
Or, to go directly to the sessions object:
var result = `{
"about": {
"name": "API",
"version": "2018.1.25.1",
"method": "get"
},
"sessions": {
"0": {
"sessionid": "c6fac08ad020cd10c377b77b81aac2ed19c08111",
"id": "121667",
"geolat": "51.9125118",
"geolon": "-2.1210269"
},
"1": {
"sessionid": "4f3da85c4905ee8c2a57ac48a22184b93fc2f680",
"cid": "122589",
"chatstarted": "2018-02-24 23:41:51",
"geolat": "51.9125118",
"geolon": "-2.1210269"
}
},
"rescode": "200",
"executed": "nokeyfound-",
"queries": "5"
}`;
resultObj = JSON.parse(result);
// Loop over the top-level object
for(var key in resultObj.sessions){
// Loop over the object stored in that key
for(var subKey in resultObj.sessions[key]){
// Access the sub-keys with an extra index:
console.log(subKey + " = " + resultObj.sessions[key][subKey]);
}
}

Related

Unable to iterate the response body and manipulate/filter the response object using node JS

I have below code which is going to invoke REST endpoint and return response back. I just tried to print the response.body in the console and It works perfectly fine.
var express = require('express');
var app = express();
var PORT = 8001;
var request = require('request');
var HashMap = require('hashmap');
var endPoint="http://sandbox.dev.amazon.com/idsearch/environment/amazon/";
app.get('/productId/:proId',async (req,res) => {
try
{
var headers ={
"accept":"application/json"
}
var options = {
url:endPoint.concat(req.params.proId),
headers:headers
}
request(options, (error,response,body)=> {
console.log(response.body) // It returned response as below output JSON file
res.send("STATUS CODE : 200");
});
}
catch(error)
{
throw error;
}
});
Output:
{
"<Some dynamic Content>": {
"type": "PROD-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
}
The above output contains all the responses with respective Endpoint URL which is expected. But I just want to fetch only the object contains "Status: 1". I'm just wondering that How can I manipulate the response.body object to get the below JSON as output.
Expected Output:
{
"callSummary":[
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
]
}
I just want to iterate the response.body obj and check the status as 1 if it's then I need to fetch all the details and form it as above payload. This is dynamic content but the template format is static.
I tried the below code to iterate the response.body but no luck.
var string = JSON.stringify(response.body);
var objectValue = JSON.parse(string);
var obj = objectValue.callSummary;
console.log(obj.length); // It returned undefined.
Please lead me to achieve this.
To return that json, just
res.json(response.body['<Some dynamic Content>'].callSummary);
Adding some validation and error handling would be a good idea before sending the response.
In case your key is just an example and you never know your first key value, and you always want the values of the first key
res.json(Object.values(response.body)[0].callSummary);
Object.values returns an array, so you can iterate the values if you want manage more than the first one

Differences with API's when trying to pull data

I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].

Postman: Wanted to validate data values getting from API in JSON format

I wanted to check some combinations of validations for values I am getting from API request in postmanlike
if "tracked": "Yes" then analytics > "transitTime": 239 should be present.
The snippet of API response:
{
"status": 200,
"data": [{
"id": 107267,
"branchId": "22",
"status": "1",
"googleETA": "2018-02-01 20:44:51",
"runDate": "2018-01-29",
"runOfTheDay": "1",
"ATD": "2018-01-29 14:02",
"simCarrier": "Vodafone",
"pingStatus": "Ok",
"driverName": "test",
"shipperCompanyId": "007",
"ETA": "2018-01-30 12:31:00",
"locationSource": "sim",
"created_at": "2018-01-29 07:05:54",
"updated_at": "2018-01-29 12:35:40",
"tracked": "Yes",
"analytics": {
"loadingTime": 55.62,
"unloadingTime": 0,
"transitTime": 239
},
"trackingStatusAtClosure": {
"Origin": "No",
"Transit": "No",
"Destination": "No"
}
}]
}
This is a very basic check and I would advise against using it anywhere other than practising in a local environment.
pm.test("Basic Check", () => {
var jsonData = pm.response.json().data
for(i = 0; i < jsonData.length; i++) {
if(jsonData[i].tracked === 'Yes') {
pm.expect(jsonData[i].analytics.transitTime).to.not.be.null
} else {
console.log('Tracked does not equal Yes')
}
}
})
As your data only has one item in the data array you don't really need to add the for loop but I added it in for you so you can see that the same check would run if you have more than one item. If the tracked property is 'Yes' then the test is checking if analytics.transitTime not null. Like I said, its a basic check and it's not doing a great deal but hopefully that will give you the information you need to get started.

Iterate through nested Javascript Objects from API response

I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);

Having trouble using data retrieved with json in javascript, cannot sort the array

I am trying to sort out the data I retrieved from an api with javascript.
Code :
function getResults() {
var url = $.getJSON("http://api.api.com&leagues=SOCENGPRE&lang=en&format=jsonp&callback=?", function(jsondata){;
for(var i = 0; i < jsondata.length; i++)
for(var id in jsondata[i]) {
console.log("ID - " + id);
console.log("TEAM - " + jsondata[i][id].home_team);
}
});
}
Example of data retrieved :
{
"SOCENGPRE": {
"league_name": "Barclays Premier League",
"league_phid": null,
"league_type": null,
"fixtures": [
{
"id": "64714",
"code": "SOCENGPRE",
"event_slug": "west_ham-tottenham-1401290",
"home_team": "West Ham",
"away_team": "Tottenham",
},
{
"id": "64711",
"code": "SOCENGPRE",
"event_slug": "manchester_u-sunderland-1401286",
"home_team": "Manchester U",
"away_team": "Sunderland"
}
But using my code I cannot seem to get the results I am wanting.
I want to print out every games ID and Home Team. Any insights on why is my code not working? Thank you very much in advance!
UPDATE: I have removed the extra semi-colon but it's still not printing the data for me.
UPDATE 2: Regarding the requests for the URL. When I call it in a browser I get this huge result
?({"SOCENGPRE":{"league_name":"Barclays Premier League","league_phid":null,"league_type":null,"fixtures":[{"id":"64714","code":"SOCENGPRE","event_slug":"west_ham-tottenham-1401290","start":"1399117500","home_team":"West Ham","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png","home_team_short":"","away_team":"Tottenham","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png","away_team_short":"","phid":null},{"id":"64711","code":"SOCENGPRE","event_slug":"manchester_u-sunderland-1401286","start":"1399125600","home_team":"Manchester U","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png","home_team_short":"Man U","away_team":"Sunderland","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png","away_team_short":"","phid":null},{"id":"64712","code":"SOCENGPRE","event_slug":"stoke-fulham-1401288","start":"1399125600","home_team":"Stoke","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png","home_team_short":"","away_team":"Fulham","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png","away_team_short":"","phid":null},{"id":"64706","code":"SOCENGPRE","event_slug":"aston_villa-hull-1401282","start":"1399125600","home_team":"Aston Villa","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t380.png","home_team_short":"","away_team":"Hull","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t511.png","away_team_short":"Hull","phid":null},{"id":"64710","code":"SOCENGPRE","event_slug":"newcastle-cardiff-1401287","start":"1399125600","home_team":"Newcastle","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t385.png","home_team_short":"","away_team":"Cardiff","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t524.png","away_team_short":"","phid":null},{"id":"64713","code":"SOCENGPRE","event_slug":"swansea-southampton-1401289","start":"1399125600","home_team":"Swansea","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t384.png","home_team_short":"Swansea","away_team":"Southampton","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t8482.png","away_team_short":"","phid":null},{"id":"64709","code":"SOCENGPRE","event_slug":"everton-manchester_c-1401285","start":"1399134600","home_team":"Everton","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t499.png","home_team_short":"","away_team":"Manchester C","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t383.png","away_team_short":"Man C","phid":null},{"id":"64707","code":"SOCENGPRE","event_slug":"arsenal-west_bromwich-1401281","start":"1399206600","home_team":"Arsenal","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t30773.png","home_team_short":"","away_team":"West Bromwich","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t816.png","away_team_short":"West Brom","phid":null},{"id":"64705","code":"SOCENGPRE","event_slug":"chelsea-norwich-1401283","start":"1399215600","home_team":"Chelsea","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t497.png","home_team_short":"","away_team":"Norwich","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t1438.png","away_team_short":"","phid":null},{"id":"64708","code":"SOCENGPRE","event_slug":"crystal_palace-liverpool-1401284","start":"1399316400","home_team":"Crystal Palace","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t518.png","home_team_short":"C. Palace","away_team":"Liverpool","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t381.png","away_team_short":"","phid":null},{"id":"64679","code":"SOCENGPRE","event_slug":"manchester_u-hull-1401252","start":"1399401900","home_team":"Manchester U","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png","home_team_short":"Man U","away_team":"Hull","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t511.png","away_team_short":"Hull","phid":null},{"id":"64630","code":"SOCENGPRE","event_slug":"manchester_c-aston_villa-1401198","start":"1399488300","home_team":"Manchester C","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t383.png","home_team_short":"Man C","away_team":"Aston Villa","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t380.png","away_team_short":"","phid":null},{"id":"64621","code":"SOCENGPRE","event_slug":"sunderland-west_bromwich-1401189","start":"1399488300","home_team":"Sunderland","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png","home_team_short":"","away_team":"West Bromwich","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t816.png","away_team_short":"West Brom","phid":null},{"id":"64719","code":"SOCENGPRE","event_slug":"manchester_c-west_ham-1401296","start":"1399816800","home_team":"Manchester C","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t383.png","home_team_short":"Man C","away_team":"West Ham","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png","away_team_short":"","phid":null},{"id":"64717","code":"SOCENGPRE","event_slug":"liverpool-newcastle-1401295","start":"1399816800","home_team":"Liverpool","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t381.png","home_team_short":"","away_team":"Newcastle","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t385.png","away_team_short":"","phid":null},{"id":"64720","code":"SOCENGPRE","event_slug":"norwich-arsenal-1401297","start":"1399816800","home_team":"Norwich","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t1438.png","home_team_short":"","away_team":"Arsenal","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t30773.png","away_team_short":"","phid":null},{"id":"64715","code":"SOCENGPRE","event_slug":"fulham-crystal_palace-1401293","start":"1399816800","home_team":"Fulham","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png","home_team_short":"","away_team":"Crystal Palace","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t518.png","away_team_short":"C. Palace","phid":null},{"id":"64722","code":"SOCENGPRE","event_slug":"sunderland-swansea-1401299","start":"1399816800","home_team":"Sunderland","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png","home_team_short":"","away_team":"Swansea","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t384.png","away_team_short":"Swansea","phid":null},{"id":"64723","code":"SOCENGPRE","event_slug":"tottenham-aston_villa-1401300","start":"1399816800","home_team":"Tottenham","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png","home_team_short":"","away_team":"Aston Villa","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t380.png","away_team_short":"","phid":null},{"id":"64724","code":"SOCENGPRE","event_slug":"west_bromwich-stoke-1401301","start":"1399816800","home_team":"West Bromwich","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t816.png","home_team_short":"West Brom","away_team":"Stoke","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png","away_team_short":"","phid":null},{"id":"64718","code":"SOCENGPRE","event_slug":"hull-everton-1401294","start":"1399816800","home_team":"Hull","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t511.png","home_team_short":"Hull","away_team":"Everton","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t499.png","away_team_short":"","phid":null},{"id":"64721","code":"SOCENGPRE","event_slug":"southampton-manchester_u-1401298","start":"1399816800","home_team":"Southampton","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t8482.png","home_team_short":"","away_team":"Manchester U","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png","away_team_short":"Man U","phid":null},{"id":"64716","code":"SOCENGPRE","event_slug":"cardiff-chelsea-1401292","start":"1399816800","home_team":"Cardiff","home_team_phid":null,"home_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t524.png","home_team_short":"","away_team":"Chelsea","away_team_phid":null,"away_team_logo":"\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t497.png","away_team_short":"","phid":null}]}});
Link to pastebin for easier reading of the data
Change your getResults function to be called after the JSON has been parsed, like so:
var myDataVar;
$.ajax({
url: "URL to JSON file here",
dataType: "text", //If you get an error here, change the type to "text"
success: function (data) {
myDataVar = $.parseJSON(data);
getResults();
}
});
The above code will save the JSON file's parsed data into a single variable.
It will then call a function to get the results, being this function:
function getResults() {
var fixturesLength = myDataVar.SOCENGPRE.fixtures.length - 1;
for (var i = 0; i <= fixturesLength; i++) {
console.log(myDataVar.SOCENGPRE.fixtures[i].id);
}
}
The above loop will print to the console every one of your fixtures ID's.
Test data used:
{
"SOCENGPRE": {
"league_name": "Barclays Premier League",
"league_phid": null,
"league_type": null,
"fixtures": [{
"id": "64714",
"code": "SOCENGPRE",
"event_slug": "west_ham-tottenham-1401290",
"start": "1399117500",
"home_team": "West Ham",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png",
"home_team_short": "",
"away_team": "Tottenham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png",
"away_team_short": "",
"phid": null
}, {
"id": "64711",
"code": "SOCENGPRE",
"event_slug": "manchester_u-sunderland-1401286",
"start": "1399125600",
"home_team": "Manchester U",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png",
"home_team_short": "Man U",
"away_team": "Sunderland",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png",
"away_team_short": "",
"phid": null
}, {
"id": "64712",
"code": "SOCENGPRE",
"event_slug": "stoke-fulham-1401288",
"start": "1399125600",
"home_team": "Stoke",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png",
"home_team_short": "",
"away_team": "Fulham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png",
"away_team_short": "",
"phid": null
}]
}
}
Console results:
64714
64711
64712

Categories