I am trying to read a nested JSON data where the key values are sub nested key and values but it does not seem to work. first json data from database table [column: Roles]
$json = array();
$sql = $db->query("SELECT * FROM u_info WHERE bid=".$branch);
while ($rs = $sql->fetch_assoc()) {
$rs['img'] = getImg($rs['img']);
$query = $db->query('SELECT roles FROM wp_roles WHERE userid='.$rs['id'])->fetch_assoc();
$rs['role'] = json_decode($query['roles']); // already a json format
$json[] = $rs;
}
exit(json_encode($json));// convert to json AJAX response works
Then json result as follows
{
"academics":{
"class":"true",
"employee":"false",
"students":"true",
"subject":"false",
"all":"true"
},
"exam":{
"exams":"false",
"schedule":"false",
"result":"false",
"marksheet":"false",
"all":"false"
},
"timetable":{
"class":"false",
"teacher":"false",
"all":"false"
},
"attendance":{
"students":"true",
"teacher":"true",
"all":"true"
}
}
undefined json length [JAVASCRIPT]
// parse nested json
var json = JSON.parse(data)
console.log(json.role) // works and print above json
console.log(json.role.length) // undefined
// for loop not works
for(i = 0; i < json.role.length; i++){
for(y = 0; y < json.role[i].length; y++){
// json.role.academics.class === true [if condition]
if(json.role[i][y] === true){
//......
}
}
}
The above JSON is an object which is why its length is coming undefined.
The way you are trying to read the data - the JSON response should have an array of objects referenced via "roles" property - in below format should work. Please check the response.
{
"roles": [{
"academics": {
"class": "true",
"employee": "false",
"students": "true",
"subject": "false",
"all": "true"
}
},
{
"exam": {
"exams": "false",
"schedule": "false",
"result": "false",
"marksheet": "false",
"all": "false"
}
},
{
"timetable": {
"class": "false",
"teacher": "false",
"all": "false"
}
},
{
"attendance": {
"students": "true",
"teacher": "true",
"all": "true"
}
}
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.