neuromancer
neuromancer

Reputation: 55549

Accessing JSON values in an express web server

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?

Upvotes: 1

Views: 299

Answers (1)

Pero P.
Pero P.

Reputation: 26992

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

  ...

Upvotes: 1

Related Questions