Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a JSON Array in node js

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.

An example query follows:

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}]};

I would send it to the server by:

res.contentType('application/json');
res.send(json);

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.

I´ve been trying to create the JSON array online like this:

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]});

However, the client only receives a json of size 1

Object {jugadores: Array[1]}

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

Thanks in advance, Im really struggling with this :(

Edit: Im trying now with stringy doing this, but no luck. What do I do wrong?

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);

Goals hash is filled using GET:

app.get('/player/:id', function (req, res) {   
res.contentType('application/json');
res.send( {'goals': + goals[req.params.id] } );

});

like image 251
Rafag Avatar asked Dec 08 '13 23:12

Rafag


People also ask

How do I create an array in JSON?

Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.

How do you create an array in node JS?

Creating an Array Object The first is simply by typing the array object. var array = []; Option two is to create an Array object by instantiating the Array object. var array = new Array();

How do I push JSON data into an array in node JS?

Simply use data. push(feed) , no special handling required.


3 Answers

Build up a JavaScript data structure with the required information, then turn it into the json string at the end.

Based on what I think you're doing, try something like this:

var result = [];
for (var name in goals) {
  if (goals.hasOwnProperty(name)) {
    result.push({name: name, goals: goals[name]});
  }
}

res.contentType('application/json');
res.send(JSON.stringify(result));

or something along those lines.

like image 110
Chris Tavares Avatar answered Oct 19 '22 06:10

Chris Tavares


You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.

Use JSON.stringify(object) to turn it into (a string of) JSON text.

like image 7
Quentin Avatar answered Oct 19 '22 07:10

Quentin


This one helped me,

res.format({
        json:function(){
                            var responseData    = {};
                            responseData['status'] = 200;
                            responseData['outputPath']  = outputDirectoryPath;
                            responseData['sourcePath']  = url;
                            responseData['message'] = 'Scraping of requested resource initiated.';
                            responseData['logfile'] = logFileName;
                            res.json(JSON.stringify(responseData));
                        }
    });
like image 4
Praneesh Avatar answered Oct 19 '22 06:10

Praneesh