Convert JavaScript object to JSON string and JSON object
In this quick post, you will learn how to convert JavaScript Object to JSON String and JSON object using the methods JSON.stringify() and JSON.parse().
Sometimes when you query a database and retreive a record, it might return you a JavaScript object. You might not know how to parse the values inside the object but if you print the object you might see all the values in it.
For example, I queried MongoDB using Mongoose findOne method. It returned an Object.
var user = await users.findOne({username: req.body.username}); console.log(user);
When you print the object, you can see all the values in it.
{ _id: 5e16e8a3c3775d62f3acbe72, name: 'Sudarshan Thiru', username: 'sthiru', role: 'Logistics Head', group: [ 'Leaders' ] }
But when you try to access a property inside the object, you won’t be able to.
console.log(user.role); //undefined
To convert this object to JSON object, you need to convert it to string first using JSON.stringify() and then parse it using JSON.parse().
if(user) { user = JSON.stringify(user); user = JSON.parse(user); console.log(user.role); //Logistics Head }
Once the object is converted to JSON object, you can just access its properties using period (.) like user.role.