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

});

This question is related to javascript arrays json node.js

The answer is


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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`