Skip to content

Instantly share code, notes, and snippets.

Created June 22, 2011 05:27
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
JSONDB implementation
# JSONDB - a compressed JSON format
# By Devon Govett
# Originally proposed by Peter Michaux -
# jsondb.pack converts an array of objects with the same keys (i.e. from a database)
# and flattens them into a single array, which is much smaller than the pure json
# representation where the keys are repeated for each item in the array.
# Combine with JSON.stringify to send compressed JSON data over the network.
# jsondb.unpack reverses that operation, turning the jsondb array back into
# an array of objects with the proper keys and values. Combine with JSON.parse.
jsondb =
pack: (records) ->
keys = Object.keys records[0] # pull the headers from the first row
ret = [
'JSONDB' # format identifier
keys.length # number of headers
keys... # headers
# values
for record in records
ret.push val for key, val of record
return ret
unpack: (array) ->
return null unless array[0] is 'JSONDB' # check format identifier
numKeys = array[1]
pos = numKeys + 2
keys = array[2...pos]
ret = []
cur = {}
for val, i in array[pos...]
if i > 0 and i % numKeys is 0
ret.push cur
cur = {}
key = keys[i % numKeys]
cur[key] = val
ret.push cur
return ret
Copy link

transforms [{ foo: "bar", baz: "boo" }, { foo: "123", baz: "hey" }] into ["JSONDB", 2, "foo", "baz", "bar", "boo", "123", "hey"]

Copy link

DBJDBJ commented Aug 19, 2011

why not just using something like ?

Copy link

Cool stuff.. But only prob for now is with something like this: [{ name: "so and so", comments: [{comment: "blah blah", by: "someone", likes: [{by: 1223}], id: 12312 }]
Nested arrays dont work. :-/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment