Accessing JSON values in an express web server

Problem

I was able to use the code in this answer to access a value in a JSON string posted to the server.

If the server gets {"MyKey":"My Value"} then the value for "MyKey" can be accessed with request.body.MyKey.

But the JSON strings that get sent to my server look like this:

[{"id":"1","name":"Aaa"},{"id":"2","name":"Bbb"}]

I could not find a way to access anything in that. How do you do it?

Problem courtesy of: neuromancer

Solution

request.body is a standard JavaScript object and in your case a vanilla JavaScript array. You would just handle request.body like you would any JavaScript Array object. e.g.

app.post('/', function(request, response){
  var users = request.body;
  console.log(users.length);   // the length of the array

  var firstUser = users[0];    // access first element in array
  console.log(firstUser.name); // log the name

  users.forEach(function(item) { console.log(item) }); // iterate the array logging each item

  ...
Solution courtesy of: Pero P.

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.