Creating a JSON Array in node js

前端 未结 3 540
北荒
北荒 2021-02-07 14:08

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

相关标签:
3条回答
  • 2021-02-07 14:34

    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));
                            }
        });
    
    0 讨论(0)
  • 2021-02-07 14:46

    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.

    0 讨论(0)
  • 2021-02-07 14:53

    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.

    0 讨论(0)
提交回复
热议问题