How to get specific data from nested JSON - javascript

I'm trying to get the nested station names using jQuery and display the names in a 'div'. I'm able to display the contents of 'jObject' however, I'm unable to get to the specific station name.
This is what i have tried so far.
$.ajax({
url: "https://transportapi.com/v3/uk/tube/stations/near.json?app_id=appid&app_key=key&lat=" + lat + "&lon=" + lng + "&page=1&rpp=5",
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
//console.log(data);
var jObject = data.stations;
// $('#stationName').append(JSON.stringify(jObject));
$.each(jObject.name, function(index, element) {
$('#stationName').append(JSON.stringify(jObject.name));
});
}
});
JSON structure
{
"minlon": -0.23437,
"minlat": 51.434842,
"maxlon": -0.03437,
"maxlat": 51.634842,
"searchlon": -0.13437,
"searchlat": 51.534842,
"page": 1,
"rpp": 1,
"total": 147,
"request_time": "2018-03-09T17:15:22+00:00",
"stations": [
{
"station_code": "MCR",
"atcocode": "9400ZZLUMTC",
"name": "Mornington Crescent",
"mode": "tube",
"longitude": -0.13878,
"latitude": 51.53468,
"lines": [
"northern"
],
"distance": 492
}
]
}

You should use $each on jObject and not on jObject.name. And you need to specify index while getting name as stations is an array of objects or just use element.name
var data={
"minlon": -0.23437,
"minlat": 51.434842,
"maxlon": -0.03437,
"maxlat": 51.634842,
"searchlon": -0.13437,
"searchlat": 51.534842,
"page": 1,
"rpp": 1,
"total": 147,
"request_time": "2018-03-09T17:15:22+00:00",
"stations": [
{
"station_code": "MCR",
"atcocode": "9400ZZLUMTC",
"name": "Mornington Crescent",
"mode": "tube",
"longitude": -0.13878,
"latitude": 51.53468,
"lines": [
"northern"
],
"distance": 492
}
]
};
var jObject = data.stations;
$.each(jObject, function(index, element) {
console.log(jObject[index].name);
console.log(element.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

There are a few things wrong in your code:
$.each() will iterate on an array, since you already define data.stations as jObject, you need to iterate in that array.
$.each function takes to parameters index and element, the first one is the position of the element in the array, and the second has the element itself.
So the code will be:
var jObject = data.stations;
$.each(jObject, function(index, element) {
$('#stationName').append(element.name);
});
Check the JSFIDDLE

Related

Can't loop through JSON data

I'm a real noob when it comes to JSON. Any help on the following would be fantastic.
console.log(obj.id); in the code below returns nothing in the console - I need to understand why? I expect it two log two things in the console based on the JSON data.
JS:
var matchTeamAStatsJSON
$.ajax({
type: 'GET',
url: 'http://www.website.com/apipathblahblahblah',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
matchTeamAStatsJSON = data;
console.log(matchTeamAStatsJSON);
for(var i = 0; i < matchTeamAStatsJSON.length; i++) {
var obj = matchTeamAStatsJSON[i];
console.log(obj.id);
}
}
})
JSON:
{
"records": [
{
"id": "recGWUWqwjUNLpekA",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-22T18:16:56.000Z"
},
{
"id": "recx5pMFpxnRwR4La",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-19T11:35:11.000Z"
}
]
}
You could use Array.prototype.forEach() and do:
const data = {"records": [{"id": "recGWUWqwjUNLpekA","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-22T18:16:56.000Z"},{"id": "recx5pMFpxnRwR4La","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-19T11:35:11.000Z"}]};
data.records.forEach(obj => console.log(obj.id));
If the JSON example you posted below is the response from the GET request, data is equal to "records" which doesn't have an and "id" property. However, each instance of the array it contains does.
You need to get inside that array first and then get the "id" property of each element: console.log(obj.records[i].id) should get you want.
Hope this helps!

Get values from array of objects angularjs, it returns only last item

I want to get values from array of objects using angular.forEach
exactly every value of element in every item. When I use angular.forEach function and loop the array of objects it only return the values of the last item. I spent hours in searching and thinking to get a solution but in vain.
Please get a look in my code:
This is the array of objects from json file that I want to get values from.
data.json:
[
{
"platform": "web-desktop",
"cdn": 4.3673292887e+10,
"p2p": 5.667683381e+09,
"total": 4.9340976268e+10,
"upload": 5.774321084e+09,
"percentage": 12,
"viewers": 1,
"maxViewers": 10,
"averageViewers": 1.5725853094274147,
"trafficPercentage": 69.49888073943228,
"live": "unknown"
},
{
"platform": "android",
"cdn": 1.7035777808e+10,
"p2p": 1.526916976e+09,
"total": 1.8562694784e+10,
"upload": 2.753179184e+09,
"percentage": 9,
"viewers": 1,
"maxViewers": 12,
"averageViewers": 1.416065911431514,
"trafficPercentage": 26.14635154335973,
"live": "unknown"
},
{
"platform": "ios",
"cdn": 2.994960132e+09,
"p2p": 9.6722616e+07,
"total": 3.091682748e+09,
"upload": 3.3788984e+07,
"percentage": 4,
"viewers": 1,
"maxViewers": 3,
"averageViewers": 1.152542372881356,
"trafficPercentage": 4.354767717207995,
"live": "unknown"
}
]
controller.js:
'use strict';
var app= angular.module('app');
app.controller('MainController',['$scope', '$http', MainController]);
function MainController ($scope, $http) {
var request = {
method: 'get',
url: 'data.json',
dataType: 'json',
contentType: "application/json"
};
$scope.arrData = new Array;
$http(request)
.then(function onSuccess(jsonData) {
// LOOP THROUGH DATA IN THE JSON FILE.
angular.forEach(jsonData.data, function (item) {
//Get data in each object
$scope.arrData = Object.keys(item).map(function(key){return item[key]});// get all values
});
console.log($scope.arrData);
});
}
Here is the result:
["ios", 2994960132, 96722616, 3091682748, 33788984, 4, 1, 3, 1.152542372881356, 4.354767717207995, "unknown"]
Or, I want to get all of this each item. What should I add to my code to make it work! Thanks.
You are overwriting $scope.arrData in every iteration of forEach
Use map() instead of forEach() and return your keys mapping in the outer map() callback
$scope.arrData = jsonData.data.map(function(item) {
return Object.keys(item).map(function(key) {
return item[key]
});
});

apply for loop on json response (multidimensional) to get value

{
"Search": [{
"Title": "Batman Begins",
"Year": "2005",
"imdbID": "tt0372784",
"Type": "movie",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg"
}, {
"Title": "Batman",
"Year": "1989",
"imdbID": "tt0096895",
"Type": "movie",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"
}],
"totalResults": "291",
"Response": "True"
}
Above is my json response. I want to get title values by using jQuery.
I tried below code... I'm sending request each time when user insert character in text box (on keyup):
url = "https://www.omdbapi.com/?s=" + value;
$.getJSON(url, {
get_param: 'value'
}, function(data) {
$.each(data, function(index, element) {
//console.log(data);
});
for (var prop in data) {
var item = data[prop];
for (var d in item) {
var title = item[d];
console.log(title);
}
}
});
You can use Jquery.each() function to iterate over both arrays and object.
It takes to arguments either array or object as the first argument and a callback function.
since the response is in form of an object you need to run another Jquery.each() on the array holding the objects if you want to implement some logic before that, or just run Jquery.each() on the array it's self:
Here is a sample code that prints the titles on the console:
$.getJSON(url, { get_param: 'value' }, function(data) {
$.each(data.Search, function(index, value) {
console.log(value.Title);
});
});
And here is a JSFiddle
$.each(data.Search, function(obj){
alert(obj.Title);
});

how to effeciantly format json data

I am trying to format json data in the most efficient way. I need to format 2 different keys in a object. both are strings
I made a fiddle with the json
fiddle
var json = [
{
"Id": 1,
"ReportId": 1,
"ReportName": "HBO: {MSA}"
"QueueDate": "2015-08-25T17:16:54.233",
"Parameters": "<xml><CBSA>Abilene, TX</CBSA><CBSASK>3</CBSASK><CBSAID>1203</CBSAID><CBSACode>10180</CBSACode><MonthNumber>6</MonthNumber><Month>June</Month><Year>2015</Year><FromDate>06/01/2014</FromDate><ToDate>06/01/2015</ToDate></xml>"
},
{
"Id": 2,
"ReportId": 2,
"ReportName": "HBO:{Marvin}"
"QueueDate": "2015-08-25T17:20:50.463",
"Parameters": "<xml><CBSA>Abilene, TX</CBSA><CBSASK>3</CBSASK><CBSAID>1203</CBSAID><CBSACode>10180</CBSACode><MonthNumber>6</MonthNumber><Month>June</Month><Year>2015</Year><FromDate>06/01/2014</FromDate><ToDate>06/01/2015</ToDate></xml>"
},
{
"Id": 3,
"ReportId": 2,
"ReportName": "HBO:{Marvin}"
"QueueDate": "2015-08-25T17:23:58.377",
"Parameters": "<xml><CBSA>Abilene, TX</CBSA><CBSASK>3</CBSASK><CBSAID>1203</CBSAID><CBSACode>10180</CBSACode><MonthNumber>6</MonthNumber><Month>June</Month><Year>2015</Year><FromDate>06/01/2014</FromDate><ToDate>06/01/2015</ToDate></xml>"
}
]
I need to end up with:
ReportName: 'MSA',
Parameters: 'Abilene, Tx'
You can use $.parseXML() to convert the xml string to an xml document object, then wrap that in $() to use jQuery traverse methods on it
$.each(json, function (_, item) {
var $xml = $($.parseXML(item.Parameters));
var cbsa = $xml.find('CBSA').text();
$('body').append($('<p>').text(cbsa));
});
Reference: parseXML() docs
DEMO

JSON formatting drill down issue

I am using dojo's arrayUtil.forEach to loop through my JSON object but when I get to data.graphs.metrics it does not continue because metrics is not an array. What options do I have?
xhr("/esp/files/eclwatch/ganglia.json", {
handleAs: "json"
}).then(function(data){
arrayUtil.forEach(data.graphs, function (item, idx) {
//never gets here.
});
});
}
//json file
{
"graphs": [
{
"name": "Bar",
"metrics":{
"metric": ["metric1, metric3"],
"metric": ["metric1", "metric4", "metric5"]
},
"time": ["Hour", "Month", "Week"]
}
]
}
Making it an array instead of giving it duplicate keys would make the most sense.
"metrics": [
["metric1, metric3"],
["metric1", "metric4", "metric5"]
],

Categories