我有以下代码可以从数据库中获取一些信息:
const getDeviceUID = `SELECT Device_UID FROM Device WHERE ThingName = "${deviceName}"`;
const deviceUIDResult = await new Promise((resolve) => {
connection.query(getDeviceUID, (err, results, fields) => {
if (err) return resolve(false);
resolve(results);
});
});
我假设(我对此很陌生!)就像我这样做时一样,deviceUIDResult现在是一个JSON对象:
console.log("RES: " + JSON.stringify(deviceUIDResult));
我得到以下信息:
RES: [{"Device_UID":"xxxx-xxxx-xxxx-xxxx"}]
但是当我尝试解析它时:
deviceUIDObj = JSON.parse(deviceUIDResult)
我明白了:
SyntaxError: Unexpected token o in JSON at position 1
当我尝试提取字段时:
var myField = deviceUIDResult["Device_UID"];
它告诉我它未定义。 我在这里不明白什么?
答案 0 :(得分:2)
deviceUIDResult
是一个包含一个对象的JavaScript数组。注意方括号:
indicates an array
↓
[{"Device_UID":"xxxx-xxxx-xxxx-xxxx"}]
↑
indicates an object
因此,首先获取数组中的第一个对象:var myField = deviceUIDResult[0]["Device_UID"];