Created
June 22, 2011 05:27
-
-
Save devongovett/1039559 to your computer and use it in GitHub Desktop.
JSONDB implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
# JSONDB - a compressed JSON format | |
# By Devon Govett | |
# Originally proposed by Peter Michaux - http://michaux.ca/articles/json-db-a-compressed-json-format | |
# | |
# 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 |
why not just using something like http://marklomas.net/ch-egg/articles/lzwjs.htm ?
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
transforms
[{ foo: "bar", baz: "boo" }, { foo: "123", baz: "hey" }]
into["JSONDB", 2, "foo", "baz", "bar", "boo", "123", "hey"]