简体   繁体   English

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

[英]Write formatted JSON in Node.js

I'm using Node.js to POST JSON to PostBin but the data is being wrongly formated (as you can see here: http://www.postbin.org/1cpndqw ). 我正在使用Node.js将JSON POST到PostBin但是数据被错误地格式化(正如你在这里看到的那样: http//www.postbin.org/1cpndqw )。

This is the code I'm using for tesT: 这是我用于tesT的代码:

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();

Use JSON.stringify(object, null, 4) where 4 is the number of spaces to use as the unit of indentation. 使用JSON.stringify(object, null, 4)其中4是要用作缩进单位的空格数。 You can also use "\\t" if you want tabs. 如果需要选项卡,也可以使用"\\t" This is actually part of the ECMAScript 5 specification , and is documented on MDN . 这实际上是ECMAScript 5规范的一部分 ,并在MDN上记录

Well, primarily because JSON doesn't care how it's formatted, and you aren't doing any formatting yourself. 好吧,主要是因为JSON不关心它是如何格式化的,而且你自己也没有做任何格式化。 What you need is a javascript prettyprinter, if you care, but the first question is "Why do you care?" 你需要的是一个javascript prettyprinter,如果你关心,但第一个问题是“你为什么关心?”

Here's a prettyprinting code from the Javascript Recipes. 这是来自Javascript Recipes的漂亮代码。

Actually there's a whole bunch of different examples here on SO. 实际上,有不同的例子一大堆这里的SO。

UPDATE UPDATE

Okay, so now it's doing what you want, let's ask if you're doing the right thing. 好的,现在它正在做你想做的事情,让我们问你是否正在做正确的事情。 As several people have pointed out, you needn't transmit those extra newlines and tabs, or spaces; 有几个人指出,你不需要传输那些额外的换行符和制表符或空格; the efficiency cost is small, probably in the neighborhood of 2-5 percent, but you never know when you might need a couple percent. 效率成本很小,可能在2-5%附近,但你永远不知道何时可能需要几个百分点。

On the other hand, I agree completely that it's a lot more convenient to be able to read the JSON output as prettyprinted text. 另一方面,我完全同意能够将JSON输出作为漂亮的文本读取更方便。 But there's another solution -- you're still probably using a browser to look at these results, so instead of prettyprinting it for transmission, use a client-side prettyprinter. 但是还有另一种解决方案 - 你仍然可能使用浏览器来查看这些结果,因此不要使用浏览器进行传输,而是使用客户端的prettyprinter。 I use JSONView for Chrome and JSONView in Firefox. 我在Firefox中使用JSONView for ChromeJSONView Many debuggers will also prettyprint the JSON results for you as well. 许多调试器也会为您提供相应的JSON结果。

I used a two step process that I found to work: 我使用了一个我发现工作的两步过程:

var output = JSON.parse(insert_json_here);
var print_to_file = JSON.stringify(output, null, "\t")

你应该检查下划线-cli - 它是一个用于检查和处理JSON数据的命令行工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM