Reputation: 1115
[{
"SchoolId":"015-08-0034-009-37",
"SubjectId":"08-0034-00613",
"Student":[
{"StudentId":"T-15981","StudentName":"John"},
{"StudentId":"T-15982","StudentName":"Paul"}
]
}]
I have a json format like this one from my php json_encode. I am getting the data like this
for (var i = 0; i < data.length; i++) {
console.log(data.[i].SchoolId);
console.log(data.[i].SubjectId);
}
and i want to get the value of
{"StudentId":"T-15981","StudentName":"John"},
{"StudentId":"T-15982","StudentName":"Paul"}
How to get the value of the two entries?Any idea is appreciated
UPDATE
success: function(data) {
for (var i = 0; i < data.student.length; i++) {
console.log(data.student[i].StudentId);
console.log(data.student[i].SchoolId);
}
},
this is a print_r i got from ajax response by changing datatype from json to html.this is the output in network>XHR>Response
Array
(
[0] => Array
(
[SchoolId] => 015-08-0034-009-37
[SubjectId] => 08-0034-00613
[Student] => Array
(
[0] => Array
(
[StudentId] => 015-08-0034-009-37
[firstname] => Chona
[lastname] => Sy
[middleinitial] => D
)
[1] => Array
(
[StudentId] => 015-08-0034-009-37
[firstname] => Alona
[lastname] => Sy
[middleinitial] => D
)
)
)
[1] => Array
(
[SchoolId] => 015-08-0034-009-38
[SubjectId] => 08-0034-00613
[SupersededProperty] => Array
(
[0] => Array
(
[StudentId] => 015-08-0034-009-36
[firstname] => Edith
[lastname] => Sy
[middleinitial] => D
)
)
)
)
Upvotes: 1
Views: 115
Reputation: 8660
You problem is that you have an array inside an array. This results in the square brackets [{...}] around your json.
Array
(
[0] => Array
(
...
You shouldn't echo the first array.
For example it seems like now you have
echo json_encode(array($data));
And instead you should have
echo json_encode($data);
As a last resorst try echoing $data[0];
Also see this
Upvotes: 0
Reputation: 7622
var data = [{
"SchoolId":"015-08-0034-009-37",
"SubjectId":"08-0034-00613",
"Student":[
{"StudentId":"T-15981","StudentName":"John"},
{"StudentId":"T-15982","StudentName":"Paul"}
]
}]
for(var i=0; i<data[0].Student.length; i++){
var StudentData = data[0].Student[i];
alert(StudentData.StudentId);
}
Upvotes: 0
Reputation: 3305
You can find working example in FIDDLE
JS code
var e = {
"Student":[
{"StudentId":"T-15981","StudentName":"John"},
{"StudentId":"T-15982","StudentName":"Paul"}
],
"SchoolId":"015-08-0034-009-37",
"SubjectId":"08-0034-00613",
};
for(var i=0; i<e.Student.length; i++){
alert('StudentId = ' + e.Student[i].StudentId + '; StudentName = ' + e.Student[i].StudentName);
}
Upvotes: 1