1

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

3
  • 1
    You JSON is an array, so probably all your accesses will start with response[0].credentials. Commented Nov 3, 2016 at 6:26
  • When i tried response[0].credentials it gave me output as ` [object Object]` . Commented Nov 3, 2016 at 6:28
  • Because this again is an array, which you have to access basically in the same way. Commented Nov 3, 2016 at 6:50

2 Answers 2

3

After looking at above answer i got some clue and i think this should work as well, this save time of iteration for me as the datastructure will return only one json object for respective credentials match (as same credentials cannot be there in DB).

   let response = JSON.parse(result);
   var data=response[0].credentials;
   let username = data[0].username;
   let password = data[0].password;
   console.log("username : " +username + "password : " +password );
Sign up to request clarification or add additional context in comments.

2 Comments

Yes..if you have only one user, there's no need to iterate.
A simpler method is here : jsfiddle.net/j7ya1L97/3 .You must return json without array.
1

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

3 Comments

It works, so is this the most efficient way to access data?
@Sohan,yes,because we have an array called credentials and must to iterate it.
@Sohan, another method is using forEach function. Here is an solution: jsfiddle.net/j7ya1L97/2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.