任何想法,为何以下html-永远在JSON.parse(..)上阻塞 (我正在尝试从IoT服务器解析json响应json似乎有效,但是解析被冻结了)
<html>
<body>
<div id="iot_data_dump"></div>
<script>
var data1 = {
"thing": 1000,
"last": [
{"t": 1541239266580, "r": 96, "d": [ 138, 47, 188, 0, 0, 18, 0, 0] },
{"t": 1541236276321, "r": 97, "d": [ 140, 49, 187, 0, 0, 17, 0, 0] },
{"t": 1541236161222, "r": 98, "d": [ 140, 49, 187, 0, 0, 18, 0, 0] }
]
};
function iot_json_function(data) {
var json_data = JSON.parse(data);
var out = "Thing: " + json_data.thing + "<br>";
for (line in json_data.last) {
out += "&nsbp;Time: " + line.t + "<br>";
out += "&nsbp;Signal Strength: " + line.r + "<br>";
out += " Data: "
for (val in line.d) {
out += val + " ";
}
out += "<br>"
}
document.getElementById("iot_data_dump").innerHTML = out;
}
iot_json_function(data1);
</script>
</body>
</html>
答案 0 :(得分:1)
它不会冻结,会引发错误:
SyntaxError:JSON中位置1处的意外令牌o
示例:
var data1 = {
"thing": 1000,
"last": [
{"t": 1541239266580, "r": 96, "d": [ 138, 47, 188, 0, 0, 18, 0, 0] },
{"t": 1541236276321, "r": 97, "d": [ 140, 49, 187, 0, 0, 17, 0, 0] },
{"t": 1541236161222, "r": 98, "d": [ 140, 49, 187, 0, 0, 18, 0, 0] }
]
};
function iot_json_function(data) {
var json_data = JSON.parse(data);
var out = "Thing: " + json_data.thing + "<br>";
for (line in json_data.last) {
out += "&nsbp;Time: " + line.t + "<br>";
out += "&nsbp;Signal Strength: " + line.r + "<br>";
out += " Data: "
for (val in line.d) {
out += val + " ";
}
out += "<br>"
}
document.getElementById("iot_data_dump").innerHTML = out;
}
try {
iot_json_function(data1);
} catch (e) {
console.error(e.message);
}
那是因为您没有将JSON传递到iot_json_function
中,而是传递了一个对象。由于它不是JSON(字符串),因此JSON.stringify
尝试将其转换为字符串,并获得"[object Object]"
,它不是有效的JSON,因此会失败。
JSON是用于数据交换的文本符号。 (More here.)如果要处理JavaScript源代码,而不要处理 string ,那么就不涉及JSON。