title: Serializing JSON tersely with a max line length
body: <p>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:</p>
  
  <p><a href="http://docs.sendgrid.com/documentation/api/smtp-api/developers-guide/" rel="nofollow">http://docs.sendgrid.com/documentation/api/smtp-api/developers-guide/</a></p>
  
  <p>They suggest doing this:</p>
  
  <pre><code>$js =~ s/(.{1,72})(\s)/$1\n   /g;
  </code></pre>
  
  <p>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.</p>
  
  <p>Now I'm using Ruby and I can do something like:</p>
  
  <pre><code>JSON.generate(@hash, options)
  </code></pre>
  
  <p>Where options provide different formatting options documented at <a href="http://flori.github.com/json/doc/classes/JSON.html#method-i-generate" rel="nofollow">http://flori.github.com/json/doc/classes/JSON.html#method-i-generate</a>.  But none of those give me what I want, which is terse JSON with a newline every once in a while.</p>
  
  <p>Any ideas?</p>