Reputation: 181
I am trying to get the array data in a JSON response. The following is my JSON response and I need to get date
and stallNo
from the data
array.
{
"operation": "AnodeSet",
"stageMap": {
"stop": 5,
"adders": 4
// ...
},
"anodeProb": [
{
"name": "hello",
"index" : "hii"
}
],
"data" : [
{
"operation" : "AnodeSet",
"stallNo: 7",
"date" : "21/12/2015"
}
]
}
Upvotes: 0
Views: 6296
Reputation: 180
angular.forEach(json.data, function(value) {
console.log(value.date);
console.log(value.stallNo);
});
Upvotes: 0
Reputation: 1510
I assumed your JSON is not parsed string.
var JSONstr='{\
"operation": "AnodeSet",\
"stageMap": {\
"stop": 5, \
"adders": 4\
},\
"anodeProb": [\
{ \
"name": "hello", \
"index" : "hii" \
}\
],\
"data" : [\
{ \
"operation" : "AnodeSet", \
"stallNo": 7, \
"date" : "21/12/2015" \
}\
]\
}';
var obj = JSON.parse(JSONstr);
console.log(obj.data[0].date, obj.data[0].stallNo);
You can use my sandbox for check to check how it works: http://jsbin.com/xugahatiwo/1/edit?js,console
Greets
Upvotes: 0
Reputation: 74738
If you are searching for angularjs solution then you can use angular.forEach
:
angular.forEach(json.data, function(item, key) {
console.log(item.stallNo);
console.log(item.date);
});
use the above one if you have more than one objects in your response. Although works for single objec too.
Upvotes: 1
Reputation: 588
You can use the method from underscore.js like below, Link for reference
_.pluck(yourObject.data, 'stallNo');
_.pluck(yourObject.data, 'date');
Output will be [7,10,12, ...], [21/12/2015, ...](until length of your data object)
Upvotes: 0
Reputation: 14027
I guess it's very simple
suppose response in an object
var object={
"operation": "AnodeSet",
"stageMap": {
"stop": 5,
"adders": 4
// ...
},
"anodeProb": [
{ "name": "hello", "index" : "hii" }
],
"data" : [
{ "operation" : "AnodeSet", "stallNo: 7", "date" : "21/12/2015" }
]
}
Then you need to track your requirement:-
object-->
-->data(array)
-->index[0,1,2.....n]
-->Keys you want.
var date = object.date[0].date;
var stallNo = object.date[0].stallNo;
Upvotes: 0
Reputation: 337560
If there is always only 1 element returned in the data
array you can retrieve it by index:
var date = json.data[0].date;
var stallNo = json.data[0].stallNo;
If there could be multiple elements in the array you would need to loop over them:
for (var i = 0; i < json.data.length; i++) {
var date = json.data[i].date;
var stallNo = json.data[i].stallNo;
// use the above values as required...
}
Upvotes: 2