使用最大行长简洁地序列化JSON [英] Serializing JSON tersely with a max line length

查看:126
本文介绍了使用最大行长简洁地序列化JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在生成一个可能很长的JSON字符串,以用于Sendgrid的SMTP API.因为它将作为SMTP标头使用,所以它应该具有最大的行长(建议为72,但绝对不能超过1000).末尾的文档中描述了一种幼稚的解决方案:

So I'm generating a potentially lengthy JSON string for use in Sendgrid's SMTP API. Because it is going as an SMTP header, it should have a maximum line length (recommended 72, but absolutely no longer than 1000). One naive solution is described in the documentation at the end of:

http://docs.sendgrid.com/documentation/api /smtp-api/developers-guide/

他们建议这样做:

$js =~ s/(.{1,72})(\s)/$1\n   /g;

但是我不喜欢这样,因为它可以在有意义的空格内拆分.此外,在空间很少且相距甚远的情况下,性能似乎非常糟糕.

But I don't like that because it could split inside a string where whitespace is meaningful. Furthermore, performance when spaces are few and far between seems like it could be pretty terrible.

现在我正在使用Ruby,我可以做类似的事情:

Now I'm using Ruby and I can do something like:

JSON.generate(@hash, options)

其中的选项提供了不同的格式设置选项,这些格式选项记录在 http: //flori.github.com/json/doc/classes/JSON.html#method-i-generate .但是这些都不给我我想要的东西,那是偶尔使用换行符的简洁JSON.

Where options provide different formatting options documented at http://flori.github.com/json/doc/classes/JSON.html#method-i-generate. But none of those give me what I want, which is terse JSON with a newline every once in a while.

有什么想法吗?

推荐答案

options = {
  indent:'',
  space:"\n",
  space_before:"\n",
  object_nl:"\n",
  array_nl:"\n",
}

这会将换行符放置在不会影响JSON语义的每个位置,并禁用任何缩进.

This puts a newline at every place where doing so won't affect the semantics of the JSON, and disables any indentation.

这不是简洁也不友好,但是换行符只是多余的1个字符,因此拥有很多换行符不会以任何实际的方式影响性能.它还可以在不影响字符串内容的情况下为您提供最短的行.您可能应该检查它们以确保它们都在长度限制内.

It's not terse and not human friendly, but a newline is just 1 extra character, so having a lot of them won't affect performance in any real way. It also gives you the shortest possible lines without affecting the content of your strings. You should probably check those to make sure they're all under the length limit.

这篇关于使用最大行长简洁地序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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