【问题标题】:Getting proper json output from restify从 restify 获取正确的 json 输出
【发布时间】:2016-02-05 20:23:27
【问题描述】:

我有一个 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()引起的?

编辑:我自己找到了答案。请参阅提供的答案。

【问题讨论】:

    标签: javascript mysql json node.js restify


    【解决方案1】:

    不需要 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();
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      相关资源
      最近更新 更多