Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing JSON tersely with a max line length

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?

like image 235
gtd Avatar asked Nov 13 '22 03:11

gtd


1 Answers

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.

like image 131
Christophe Biocca Avatar answered Dec 09 '22 12:12

Christophe Biocca