Kavitha K
Kavitha K

Reputation: 75

How to get the values from json object in nodejs

I am not able to get the values from json object in nodejs.I am getting always undefined message for json object key.May be this response sync or asyn in nodejs.I do not know how to resolve this issue.Anyone can resolve this issue?

data.controller.js

module.exports.insertData = (req, res, next) => { 
let collectionName = req.query.collection; 
let collectionData = req.query.collectionData;

    console.log(collectionData);//Getting {"product_name":"test","product_weight":"45","product_price":"362"}

    console.log(collectionData.product_name); //Getting undefined
    console.log(collectionData.product_price); //Getting undefined
    console.log(collectionData.product_weight);  //Getting undefined
 }

Upvotes: 0

Views: 87

Answers (2)

Shankar Singh
Shankar Singh

Reputation: 38

You can use lodash library for your util methods,

npm i lodash

After installation:

import _ from 'lodash';

const productName = _.get(collectionData, 'product_name', 'default_name')

console.log(productName);

Upvotes: 0

Albert
Albert

Reputation: 76

Use JSON.parse().

let collectionDataJSON = JSON.parse(collectionData);

console.log(collectionDataJSON.product_name);

Upvotes: 1

Related Questions