从 restify 获得正确的 json 输出

Getting proper json output from restify

我有一个 restify API 来打印 MySQL 查询的 json 输出。下面是相关的代码部分;

server.get('/echo/:message', function (req, res, next) {
    connection.connect();
    connection.query('SELECT * FROM hkh.monthly_curves LIMIT 2', function(err, rows, fields) {
        if (err) throw err;

        var jsonString = JSON.stringify(rows);
        console.log(jsonString);
        res.send(jsonString);
    });
    connection.end();
    return next();
});

console.log(jsonString); 的输出是正确的 json 字符串。在这里;

[
   {
      "id":1,
      "date_transacted":"1998-05-31T16:00:00.000Z",
      "tbill_1_year":2.6,
      "tbond_2_year":3.15,
      "tbond_5_year":3.94,
      "tbond_10_year":5.3
   },
   {
      "id":2,
      "date_transacted":"1998-06-30T16:00:00.000Z",
      "tbill_1_year":3.2,
      "tbond_2_year":3.58,
      "tbond_5_year":4.04,
      "tbond_10_year":5.43
   }
]

在浏览器上,res.send(jsonString); 的 json 输出格式不正确。看起来像这样;

"[{\"id\":1,\"date_transacted\":\"1998-05-31T16:00:00.000Z\",\"tbill_1_year\":2.6,\"tbond_2_year\":3.15,\"tbond_5_year\":3.94,\"tbond_10_year\":5.3},{\"id\":2,\"date_transacted\":\"1998-06-30T16:00:00.000Z\",\"tbill_1_year\":3.2,\"tbond_2_year\":3.58,\"tbond_5_year\":4.04,\"tbond_10_year\":5.43}]"

如何使浏览器 json 输出的格式正确?我觉得很奇怪,同一个变量 jsonString 可以看起来不同。由 res.send()?

引起

编辑:我自己找到了答案。查看提供的答案。

不需要JSON.stringify() mysql 输出。 res.send() 将执行 json.stringify() 本身。在问题的原始代码中,额外的 \ 字符是由 JSON.stringify() 造成的 mysql 输出两次。

 server.get('/echo/:message', function (req, res, next) {
        connection.connect();
        connection.query('SELECT * FROM hkh.monthly_curves LIMIT 2', function(err, rows, fields) {
            if (err) throw err;

            //var jsonString = JSON.stringify(rows);
            //console.log(jsonString);
            res.send(rows);
        });
        connection.end();
        return next();
    });