我正在尝试读取嵌套的JSON数据,其中键值是子嵌套的键和值,但它似乎不起作用。 数据库表中的第一个json数据[列:角色]
$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
然后将json结果如下
{
"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"
}
}
未定义的json长度[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){
//......
}
}
}
答案 0 :(得分:0)
上面的JSON是一个对象,这就是为什么其长度不确定的原因。
您尝试读取数据的方式-JSON响应应具有通过“ roles”属性引用的对象数组-以下格式应能工作。请检查回复。
{
"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"
}
}
]
}