How to convert a String into JSON object in NodeJS

Just a few days ago I needed to do this and I found this useful function. Very simple:

var jsonStr = "{"firstName":"Siry", "lastName":"Mazari"}";

console.log('JSON String: %s', jsonStr);

var jsonObj = JSON.parse(jsonStr);

console.log('First Name: %s', jsonObj.firstName);
console.log('Last Name: %s', jsonObj.lastName);

The variable jsonStr contains a String representation of a JSON object. The variable jsonObj contains the object that was parsed from jsonStr. This is why we can access its properties.

Hope it helps!

Sources:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: