简体   繁体   中英

How to parse JSON in node js

I have this JSON array, and what I want is to get the password field alone

var user = [ { _id: 5902086ecbc0dd11e4870fd9,
    password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',
    email: 'jv100@gmail.com',
    lastName: 'v',
    firstName: 'j',
    updatedDate: 2017-04-27T15:04:14.483Z,
    createdDate: 2017-04-27T15:04:14.483Z } ]

I tried to parse it using this code

var obj = JSON.parse(user);
console.log(user.password);

but still it is undefined.

User is already a list of objects, so you don't need to parse it. However, it is an array. So if you meant for it to be an array, you'd need to access the password by using this code:

console.log(user[0].password);

It's already an array there is nothing to parse. You can access your property via:

console.log(user[0].password);

You can't access your property with user.password because user variable is not object, it's an array, your object is stored at the zero index of your array.

You already have JSON object . hence, no need to parse it again.

DEMO

 var user = [{ _id: "5902086ecbc0dd11e4870fd9", password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi', email: 'jv100@gmail.com', lastName: 'v', firstName: 'j', updatedDate: "2017-04-27T15:04:14.483Z", createdDate: "2017-04-27T15:04:14.483Z" } ]; var password = user[0].password; console.log(password);

The variable 'user' is not a JSON array. It's an array with a single Javascript object as its element. JSON.parse(arg) can only be used to parse a JSON string to a plain Javascript object. That being said, to access the javascript object within the array, you can do:

var userData = user[0];

To access the password within the variable, userData, you can do:

var password = userData.password;

Log the password to the console with:

console.log(password);

Try This:

var user = [ {_id:'5902086ecbc0dd11e4870fd9',password: '$2a$08$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',email: 'jv100@gmail.com',lastName: 'v',firstName: 'j',updatedDate: '2017-04-27T15:04:14.483Z',createdDate:' 2017-04-27T15:04:14.483Z' } ];

var obj = user[0];
console.log(obj.password);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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