I have this JSON array, and what I want is to get the password field alone
var user = [ { _id: 5902086ecbc0dd11e4870fd9,
password: '2ドルa08ドル$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',
email: '[email protected]',
lastName: 'v',
firstName: 'j',
updatedDate: 2017年04月27日T15:04:14.483Z,
createdDate: 2017年04月27日T15: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.
5 Answers 5
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);
4 Comments
user is already an array of objects not JSON. JSON is a string representation of objects.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.
Comments
You already have JSON object. hence, no need to parse it again.
DEMO
var user = [{ _id: "5902086ecbc0dd11e4870fd9",
password: '2ドルa08ドル$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',
email: '[email protected]',
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);
Comments
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);
Comments
Try This:
var user = [ {_id:'5902086ecbc0dd11e4870fd9',password: '2ドルa08ドル$FIpkmFT1WDZggQYyBA4CVuop6pelbKBfUEJ1/KAVIV2Si9Ho1EYhi',email: '[email protected]',lastName: 'v',firstName: 'j',updatedDate: '2017-04-27T15:04:14.483Z',createdDate:' 2017年04月27日T15:04:14.483Z' } ];
var obj = user[0];
console.log(obj.password);
user[ index ].password;(user[0].password;for the first object ...).