JSON返回未定义的值

JSON returning undefined values

本文关键字:未定义 返回 JSON      更新时间:2023-09-26

我有一个问题,json输出值返回未定义。

JSON:

[ { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ]
代码:

console.log(res);
res = JSON.stringify(res);
console.log(res);
var user = {};
user.user = res.user;
user.password = res.password;
user.admin = res.admin;
console.log(user);
输出:

[ RowDataPacket { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ]
[ { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ]
{ user: undefined, password: undefined, admin: undefined }

有几点。如果这是你的json:

[ RowDataPacket { ID: 2, user: 'ngx.daniel', password: 'password', admin: 'F' } ]

不需要字符串化。当你对它进行字符串化时,你把你的对象变成了一个字符串。然后尝试访问字符串没有的属性。
1 -删除stringify
2 -这是一个数组返回与RowPacketData对象,这也是无效的json。
3 -要访问数组中的对象,首先需要访问索引。所以应该是像

这样的东西

(如果res = [ { ID: 2, user: 'ngx.daniel', password: 'Root_!$@#', admin: 'F' }])

var user = {};
user.user = res[0].user;
user.password = res[0].password;
user.admin = res[0].admin;

响应显然可以由多个项目组成(RowDataPackets)。你可以通过索引0得到第一个。并且不需要对响应进行字符串化:

console.log(res);
var user = {};
user.user = res[0].user;
user.password = res[0].password;
user.admin = res[0].admin;
console.log(user);

打印

对象{user="ngx。丹尼尔",密码= " Root_ !$ @ #",管理= " F "}