Serializing JSON tersely with a max line length

落花浮王杯 提交于 2020-01-03 19:57:36

问题


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/

They suggest doing this:

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

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

JSON.generate(@hash, options)

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.

Any ideas?


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/11231110/serializing-json-tersely-with-a-max-line-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!