0

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

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:

[ 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 }
4
  • 3
    JSON.stringify returns a string. Why do you expect a string to have a user property? Commented Sep 20, 2015 at 19:22
  • 1
    @turbopipp: That will make no difference. Commented Sep 20, 2015 at 19:22
  • JSON likes strings inside the objects, from what I remember Commented Sep 20, 2015 at 19:23
  • 1
    Your JSON syntax is wrong. It should be [ { "ID": 2, "user": "ngx.daniel", "password": "Root_!$@#", "admin": "F" } ]. Commented Sep 20, 2015 at 19:24

2 Answers 2

3

A few things. If this is your 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
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

(if 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;
Sign up to request clarification or add additional context in comments.

Comments

0

The response can apparently consist of multiple items (RowDataPackets). You can get the first via index 0. And there is no need to stringify the response:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.