节点和快速发送json格式

vyu0f0g1  于 2023-02-26  发布在  其他
关注(0)|答案(7)|浏览(130)

我正在尝试用express发送格式化的json。
下面是我的代码:

var app = express();

app.get('/', function (req, res) {
  users.find({}).toArray(function(err, results){
    // I have try both
    res.send(JSON.stringify(results, null, 4));
    // OR
    res.json(results);
  });
});

我在浏览器中得到了一个json,但是它是一个字符串,我怎样才能发送它,使它在浏览器中可读呢?

cwdobuhd

cwdobuhd1#

尝试在节点应用程序上设置“secret”属性json spaces

app.set('json spaces', 2)

上述语句将在json内容上产生缩进。

sczxawaw

sczxawaw2#

您必须将内容类型设置为application/json,如下所示

app.get('/', function (req, res) {
    users.find({}).toArray(function(err, results){
        res.header("Content-Type",'application/json');
        res.send(JSON.stringify(results, null, 4));
  });
});
cngwdvgl

cngwdvgl3#

使用type('json')设置Content-TypeJSON.stringify()的格式:

var app = express();

app.get('/', (req, res) => {
  users.find({}).toArray((err, results) => {
    res.type('json').send(JSON.stringify(results, null, 2) + '\n');
  });
});
eiee3dmh

eiee3dmh4#

考虑到服务器的资源使用和性能,从服务器发送格式化的JSON输出可能是不可取的,特别是在生产环境中。
相反,您可以找到一些方法在客户端格式化JSON输出。
如果您使用的是Chrome浏览器,您可以使用JSON FormatterJSON ViewerJSONView或其他从Chrome网上商店扩展。
Firefox从Firefox 44开始提供内置的JSON viewer
在命令行或shell脚本中使用curlwget时,可以将JSON中的结果通过管道传输到jq

$ curl http://www.warehouse.com/products | jq .
jv4diomz

jv4diomz5#

这应该能解决你的问题

var app = express();
app.set('json spaces', 4)

app.get('/', function (req, res) {
  users.find({}).toArray(function(err, results){
      res.json(JSON.parse(results));
  });
});
dced5bon

dced5bon6#

为了方便起见,您可以在路由之前运行的定制中间件中覆盖res.json
要自动格式化 * 所有 * JSON响应:

app.use('*', (req, res, next) => {
    res.json = (data) => res.type('json').send(JSON.stringify(data, null, 4))
    next()
})

app.get('/route', (req, res) => res.json({ formatted: true })

允许基于单个管线或其他逻辑自定义格式的步骤:

app.use('*', (req, res, next) => {
    res.json = (...args) => res.type('json').send(JSON.stringify(...args))
    next()
})

app.get('/tabs', (req, res) => res.json({ formatted: 'tabs' }, null, '\t')
app.get('/spaces', (req, res) => res.json({ formatted: 'spaces' }, null, 4)
app.get('/minified', (req, res) => res.json({ formatted: false })

相关问题