我正在使用.getJSON将数据提取到图形中。由于某些原因,当我尝试遍历JSON数组时,它给了我每个字符,就像它没有将其视为数组一样,但是当我将数据转储到控制台时,它是正确格式化的JSON。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$.getJSON("/getgraphdata", function(result) {
console.log(result.length);
testFunction(result);
});
</script>
</head>
<body>
<script>
function testFunction(data) {
console.log(data); // line 16
//console.log(data.length); Gives total character count.
for(var i = 0; i < data.length; i++) {
var obj = data[i];
//console.log(obj.id);
}
}
</script>
</body>
</html>
这是直接从控制台获取的数据。 (从第16行开始)
[{"id":"1375857","temperature":"78.98","humidity":"90.2","nodeName":"Bsmt_Front","timestamp":"1536424185"},{"id":"1375856","temperature":"78.98","humidity":"77.1","nodeName":"Bsmt_Back","timestamp":"1536424185"},{"id":"1375855","temperature":"77.54","humidity":"49.9","nodeName":"Living_Room","timestamp":"1536424180"},{"id":"1375854","temperature":"0","humidity":"0","nodeName":"Bsmt_Room","timestamp":"1536424179"},{"id":"1375853","temperature":"79.52","humidity":"82.7","nodeName":"Flow_Tent","timestamp":"1536424158"}]
我在这里JavaScript loop through json array?使用了最高评分的答案
如果我在第21行注释掉,则显示未定义。如果我执行console.log(obj),它将遍历数组中的每个单个字符。
所有指向它的都没有将其视为数组,但是[]在那里。
答案 0 :(得分:2)
您可以使用JSON.parse将字符串解析为javascript对象
因此您应该在event
内
testFunction