-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_minifier.coffee
More file actions
68 lines (49 loc) · 1.66 KB
/
json_minifier.coffee
File metadata and controls
68 lines (49 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
###!
JSON_Minifier
Copyright 2011 Arwid Bancewicz
Licensed under the MIT license
http://www.opensource.org/licenses/mit-license.php
@date 31 Aug 2011
@author Arwid Bancewicz http://arwid.ca
@version 0.1
###
JSON_Minifier = (->
# PRIVATE Members
getKeys = (array) ->
_(array)
.chain()
.map((obj) -> _.keys obj)
.flatten()
.union()
.value()
getValues = (array, keys = getKeys(array)) ->
_(array)
.map (obj) ->
_(keys).map (b) -> obj[b]
# PUBLIC Members
# Take a jsonArray and return a minified version
minify: (jsonArray, stringify = no) ->
# If it's a JSON string then convert it into an object by parsing it
if _(jsonArray).isString() then jsonArray = JSON.parse jsonArray
# Do the magic
keys = getKeys jsonArray
data = getValues jsonArray, keys
minified = { data: data, map: keys }
# Return the minified, stringified if asked
if stringify then JSON.stringify minified else minified
# Take a minified object or JSONString and return the original object
revert: (minified, stringify = no) ->
# If it's a JSON string then convert it into an object by parsing it
if _(minified).isString() then minified = JSON.parse minified
# Do the magic
original = _.map minified.data, (datum) ->
row = {}
_(minified.map).each (key, index) -> row[key] = datum[index]
row
# Return the original, stringified if asked
if stringify then JSON.stringify original else original
)()
# Have this utility accessible via Underscore mixins
_.mixin
JSON_minify : JSON_Minifier.minify
JSON_revert : JSON_Minifier.revert