JSON返回未定义的值 [英] JSON returning undefined values

查看:111
本文介绍了JSON返回未定义的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到json输出值返回未定义的问题.

I have a problem with a json output values returning undefined.

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:

A few things. If this is your json:

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

您不需要对它进行分类.对其进行字符串化时,会将您的对象转换为字符串.然后,您尝试访问它没有的字符串属性.
1-删除stringify
2-Thats是一个与RowPacketData对象一起返回的数组,该对象也是无效的json.
3-要访问数组中的对象,您需要首先访问索引.因此,实际上应该是

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
2 - Thats an array thats being returned with a RowPacketData object, which is also invalid json.
3 - To access an object in an array you need to first access the index. So it should really be something like

(如果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;

这篇关于JSON返回未定义的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆