gpt4 book ai didi

javascript - 在 Node.js 中编写格式化的 JSON

转载 作者:IT老高 更新时间:2023-10-28 12:43:03 25 4
gpt4 key购买 nike

我正在使用 Node.js 将 JSON POST 到 PostBin,但数据格式错误(如您在此处看到的:http://www.postbin.org/1cpndqw)。

这是我用于测试的代码:

var http = require('http');

var options = {
host: 'www.postbin.org',
port: 80,
path: '/1cpndqw',
method: 'POST'
};

var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});

req.write(JSON.stringify({ a:1, b:2, c:3 }, null, 4));
req.end();

最佳答案

使用 JSON.stringify(object, null, 4) 其中 4 是用作缩进单位的空格数。如果需要标签,也可以使用 "\t"。这实际上是 part of the ECMAScript 5 specification , 是 documented on MDN .

关于javascript - 在 Node.js 中编写格式化的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5693999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com