简体   繁体   English

JSON返回未定义的值

[英]JSON returning undefined values

I have a problem with a json output values returning undefined. 我在返回未定义的json输出值时遇到问题。

JSON: JSON:

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

CODE: 码:

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);

OUTPUT: OUTPUT:

[ 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 }

A few things. 一些东西。 If this is your json: 如果这是您的json:

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

you dont need to stringify it. 您不需要将其分类。 When you stringify it you turn your object into a string. 对其进行字符串化时,会将对象转换为字符串。 you then try to access attributes of a string, which it doesnt have. 然后,您尝试访问它没有的字符串属性。
1 - Remove the stringify 1-删除字符串
2 - Thats an array thats being returned with a RowPacketData object, which is also invalid json. 2-Thats是与RowPacketData对象一起返回的数组,该对象也是无效的json。
3 - To access an object in an array you need to first access the index. 3-要访问数组中的对象,您需要首先访问索引。 So it should really be something like 所以它真的应该像

(if res = [ { ID: 2, user: 'ngx.daniel', password: 'Root_!$@#', admin: 'F' }] ) (如果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;

The response can apparently consist of multiple items ( RowDataPackets ). 响应显然可以包含多个项目( RowDataPackets )。 You can get the first via index 0. And there is no need to stringify the response: 您可以通过索引0获得第一个。并且不需要对响应进行字符串化:

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

Which prints 哪些印刷品

Object { user="ngx.daniel", password="Root_!$@#", admin="F"} 对象{user =“ ngx.daniel”,password =“ Root _!$ @#”,admin =“ F”}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM