Sohan Sohan - 1 month ago 5
JSON Question

Parse json response in nodejs

I am beginner and learning javascript and never came across parsing json array. I have following string

[{"_id":"5810abfec95a8743ec237fab","credentials":[{"_id":"5810abfec95a8743ec237fab","username":"sam"}]}]


I tried following,

//using following middle-ware as well
let app = express();
const collectioName = "credentials";
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));

//i get 'result' from one of query from mongodb
let response = JSON.parse(result);
console.log("got res " +response.credentials);


I also tried to get data in following way

for (var i=0; i<response['credentials'].length; i++){
console.log("got res " +response['credentials'][i]);
}


I need to get the username and its value from above json response.
I want to know what is correct way to get data from such json response.

Please suggest

Answer

Please try this:

var data=response[0].credentials;
for (var i=0; i<data.length; i++){
  console.log(data[i]._id);
  console.log(data[i].username);
}

Here is jsfiddle