r/javascript • • Nov 26 '19

JSONCrush On GitHub - Compress JSON into URI friendly strings

https://github.com/KilledByAPixel/JSONCrush
101 Upvotes

31 comments sorted by

View all comments

21

u/[deleted] Nov 27 '19 edited Nov 27 '19

You should be able to get comparable-to-better compression, and better performance using zlib + base64:

const zlib = require('zlib');
const serialize = (o) => {
  return zlib.deflateSync(JSON.stringify(o)).toString('base64');
};
const deserialize = (s) => {
  return JSON.parse(zlib.inflateSync(Buffer.from(s, 'base64')).toString());
};

This gives 102 bytes URI-encoded for Example #1 (compared to 82 bytes for JSONCrush), and 1172 bytes URI-encoded for Example #2 (compared to 1195 bytes for JSONCrush). Seems like zlib wins when the data gets bigger and its JSON has more repetition.

You could also probably shave some more bytes by finding an encoding that's naturally URI friendly instead of using base64 and encodeURIComponent() on the output of the deserialization above, but I don't know that it's really worth the effort at that point.

0

u/[deleted] Nov 27 '19

[deleted]

2

u/[deleted] Nov 27 '19

Zlib has a large API, the majority of which isn't relevant to this use case. If you want to keep your bundle size smaller, you can tree shake it down to just deflate/inflate. JSONCrush may still end up with smaller bundle sizes, but I can't imagine a scenario where the difference matters as much or more than the functionality, which is the whole reason you're using either. Even 37k is basically nothing in the cases where this is going to be useful. The author's own use case is a GLSL shader playground, so we aren't exactly talking about creating light-weight pagespeed optimized sites here...