title: Creating a JSON Array in node js
body: <p>I need to create in my server written in node js a JSON string to be sent to the client when this request it. The problem is that this JSON depends on the available data in the server, thus, the size of the JSON array is not the same always. I´ve trying whole day but although I feel to be close I still dont get it.</p>
  
  <p>An example query follows:</p>
  
  <pre><code>json={"players":[
              {"name":"Messi", "goals":8},            
              {"name":"Ronaldo", "goals":22},
              {"name":"Costa", "goals":20},
              {"name":"Neymar", "goals":13},
              {"name":"Arabi", "goals":6},
              {"name":"Bale", "goals":3},
              {"name":"Toquero", "goals":0}]};
  </code></pre>
  
  <p>I would send it to the server by:</p>
  
  <pre><code>res.contentType('application/json');
  res.send(json);
  </code></pre>
  
  <p>The JSON array that I want create it depends on a hash called 'goals' where a player name is the key and a number of goals the value. Thus, if there are only 3 players, the JSON Array only should have this size.</p>
  
  <p>I´ve been trying to create the JSON array online like this:</p>
  
  <pre><code>result= "";
  for(i in goals){
      result = result+ '{ name:' + i + ", goals:" + goals[i] + '},';
  }
  result= result.substring(0, result.length - 1); 
  res.contentType('application/json');
  res.send( { 'players': [ result]});
  </code></pre>
  
  <p>However, the client only receives a json of size 1</p>
  
  <pre><code>Object {jugadores: Array[1]}
  </code></pre>
  
  <p>jugadores: Array[1]
  0: "{ nombre:Messi, goles:8},{ nombre:Ronaldo, goles:16},{ nombre:Costa, goles:10},{ nombre:Toquero, goles:0},{ nombre:Arabi, goles:2},{ nombre:Bale, goles:10},{ nombre:Neymar, goles:8}"
  length: 1</p>
  
  <p>Thanks in advance, Im really struggling with this :(</p>
  
  <p>Edit: Im trying now with stringy doing this, but no luck. What do I do wrong?</p>
  
  <pre><code>result= "players:[";
  for(i in goals){
      result= result+ '{ name:' + i + ", goals:" + goals[i] + '},';
  }
  
  result= result.substring(0, resultado.length - 1);  
  result= result + ']'
  
  res.contentType('application/json');
  myJSONstring = JSON.stringify(resultado);
  res.send(myJSONstring);
  </code></pre>
  
  <p>Goals hash is filled using GET:</p>
  
  <pre><code>app.get('/player/:id', function (req, res) {   
  res.contentType('application/json');
  res.send( {'goals': + goals[req.params.id] } );
  </code></pre>
  
  <p>});</p>