在Node.js中编写格式化的JSON [英] Write formatted JSON in Node.js

查看:167
本文介绍了在Node.js中编写格式化的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

这是我用于测试的代码:

This is the code I'm using for 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();


推荐答案

好吧,主要是因为JSON不关心它是怎么回事格式化,你自己没有做任何格式化。你需要的是一个javascript prettyprinter,如果你关心,但第一个问题是你为什么关心?

Well, primarily because JSON doesn't care how it's formatted, and you aren't doing any formatting yourself. What you need is a javascript prettyprinter, if you care, but the first question is "Why do you care?"

这是一个 prettyprinting 代码。

实际上在SO上有一大堆不同的例子这里

Actually there's a whole bunch of different examples here on SO.

更新

好的,现在它正在做你想要的,让我们问你是否做正确的事。有几个人指出,你不需要传输那些额外的换行符和制表符或空格;效率成本很小,可能在2-5%附近,但你永远不知道何时可能需要几个百分点。

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.

另一方面,我完全同意能够将JSON输出读作漂亮的文本更方便。但是还有另一种解决方案 - 你仍然可能使用浏览器来查看这些结果,因此不要使用浏览器进行传输,而是使用客户端的prettyprinter。我使用 JSONView for Chrome JSONView 。许多调试器也会为您提供相应的JSON结果。

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. 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. I use JSONView for Chrome and JSONView in Firefox. Many debuggers will also prettyprint the JSON results for you as well.

这篇关于在Node.js中编写格式化的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆