我有一个JSON对象:
var info=JSON.parse(server_response);
我跑console.log(info);
得到了这个输出:
[
[
[
"Dipu",
"Mondal",
"O Positive",
"017xxxx",
"AIS"
]
],
[
[
"dipu",
"Roy",
"O Positive",
"017xxxx",
"Electrical"
]
],
[
[
"Dhinka",
"Chika",
"O Positive",
"9038485777",
"stat"
]
]
]
跟着这个小提琴:http://jsfiddle.net/6CGh8/我试过了:
console.log(info.length); //output: 161
console.log(info[0].length); //output: 1
console.log(info[0][1]); //output: undefined
这三条线的预期输出(分别):
3
5
迪普
为什么我期待这个:
此JSON对象包含3个数组,每个数组中有5个数据,[0][1]
元素为Dipu
。
如何获得预期的输出?
答案 0 :(得分:5)
你有json编码两次,所以info只是一个文本,而不是一个数组。
info.length // length of the string
info[0].length // length of a character (1)
info[0][1] // undefined because a character is not an array
尝试var info = JSON.parse(JSON.parse(server_response))
答案 1 :(得分:1)
您的轻描淡写和JSON结构存在一些错误。
您的JSON结构需要修改为
[["Dipu","Mondal","O Positive","017xxxx","AIS"],
["dipu","Roy","O Positive","017xxxx","Electrical"],
["Dhinka","Chika","O Positive","9038485777","stat"]]
以下是示例代码段
<!doctype html>
<html lang="en">
<head>
<script>
var info = JSON.parse('[["Dipu","Mondal","O Positive","017xxxx","AIS"],["dipu","Roy","O Positive","017xxxx","Electrical"],["Dhinka","Chika","O Positive","9038485777","stat"]]');
console.log(info.length); //OP: 3
console.log(info[0].length); //OP: 5
console.log(info[0][0]); //OP: Dipu
</script>
</head>
<body>
</body>
</html>
&#13;