-
Notifications
You must be signed in to change notification settings - Fork 27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
A nicer CSON.stringify #9
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
/* | ||
Copyright (c) 2014, Groupon, Inc. | ||
All rights reserved. | ||
|
||
Redistribution and use in source and binary forms, with or without | ||
modification, are permitted provided that the following conditions | ||
are met: | ||
|
||
Redistributions of source code must retain the above copyright notice, | ||
this list of conditions and the following disclaimer. | ||
|
||
Redistributions in binary form must reproduce the above copyright | ||
notice, this list of conditions and the following disclaimer in the | ||
documentation and/or other materials provided with the distribution. | ||
|
||
Neither the name of GROUPON nor the names of its contributors may be | ||
used to endorse or promote products derived from this software without | ||
specific prior written permission. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS | ||
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | ||
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A | ||
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED | ||
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | ||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | ||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | ||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | ||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
*/ | ||
|
||
// Generated by CoffeeScript 2.0.0-beta8 | ||
module.exports = function (obj, visitor, indent) { | ||
var indentLine, indentLines, jsIdentifierRE, n, newlineWrap, serialize, tripleQuotesRE; | ||
if (typeof obj === 'undefined' || typeof obj === 'function') | ||
return; | ||
indent = function () { | ||
switch (typeof indent) { | ||
case 'string': | ||
return indent.slice(0, 10); | ||
case 'number': | ||
n = Math.min(indent, 10); | ||
if (!in$(n, [ | ||
1, | ||
2, | ||
3, | ||
4, | ||
5, | ||
6, | ||
7, | ||
8, | ||
9, | ||
10 | ||
])) | ||
n = 0; | ||
return Array(n + 1).join(' '); | ||
default: | ||
return 0; | ||
} | ||
}.call(this); | ||
if (!indent) | ||
return JSON.stringify(obj, visitor, indent); | ||
indentLine = function (line) { | ||
return indent + line; | ||
}; | ||
indentLines = function (str) { | ||
return str && str.split('\n').map(indentLine).join('\n'); | ||
}; | ||
newlineWrap = function (str) { | ||
return str && '\n' + str + '\n'; | ||
}; | ||
jsIdentifierRE = /^[a-z_$][a-z0-9_$]*$/i; | ||
tripleQuotesRE = new RegExp("'''", 'g'); | ||
obj = JSON.parse(JSON.stringify(obj, visitor)); | ||
return (serialize = function (obj) { | ||
var array, key, keypairs, object, string, val; | ||
switch (typeof obj) { | ||
case 'boolean': | ||
return obj + ''; | ||
case 'number': | ||
if (isFinite(obj)) { | ||
return obj + ''; | ||
} else { | ||
return 'null'; | ||
} | ||
case 'string': | ||
if (obj.indexOf('\n') === -1) { | ||
return JSON.stringify(obj); | ||
} else { | ||
string = obj.replace(tripleQuotesRE, "\\'''"); | ||
string = newlineWrap(indentLines(string)); | ||
return "'''" + string + "'''"; | ||
} | ||
case 'object': | ||
if (obj === null) { | ||
return 'null'; | ||
} else if (Array.isArray(obj)) { | ||
array = obj.map(serialize).join('\n'); | ||
array = newlineWrap(indentLines(array)); | ||
return '[' + array + ']'; | ||
} else { | ||
keypairs = function (accum$) { | ||
for (key in obj) { | ||
val = obj[key]; | ||
if (!key.match(jsIdentifierRE)) | ||
key = JSON.stringify(key); | ||
val = serialize(val); | ||
accum$.push('' + key + ': ' + val); | ||
} | ||
return accum$; | ||
}.call(this, []); | ||
object = keypairs.join('\n'); | ||
object = newlineWrap(indentLines(object)); | ||
return '{' + object + '}'; | ||
} | ||
} | ||
})(obj); | ||
}; | ||
function in$(member, list) { | ||
for (var i = 0, length = list.length; i < length; ++i) | ||
if (i in list && list[i] === member) | ||
return true; | ||
return false; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
# There are multiple ways to express the same thing in CSON, so trying to | ||
# make `CSON.stringify(CSON.parse(str)) == str` work is doomed to fail | ||
# but we can at least make output look a lot nicer than JSON.stringify's. | ||
module.exports = (obj, visitor, indent) -> | ||
return undefined if typeof obj in ['undefined', 'function'] | ||
|
||
# pick an indent style much as JSON.stringify does, but limited to cson legals | ||
indent = switch typeof indent | ||
when 'string' then indent.slice 0, 10 | ||
|
||
when 'number' | ||
n = Math.min indent, 10 | ||
n = 0 unless n in [1..10] # do not bail on NaN and similar | ||
Array(n + 1).join ' ' | ||
|
||
else 0 | ||
|
||
return JSON.stringify obj, visitor, indent unless indent | ||
|
||
indentLine = (line) -> indent + line | ||
|
||
indentLines = (str) -> | ||
str and str.split('\n').map(indentLine).join('\n') | ||
|
||
newlineWrap = (str) -> | ||
str and "\n#{ str }\n" | ||
|
||
jsIdentifierRE = /^[a-z_$][a-z0-9_$]*$/i | ||
tripleQuotesRE = new RegExp "'''", 'g' # some syntax hilighters hate on /'''/g | ||
|
||
# have the native JSON serializer do visitor transforms & normalization for us | ||
obj = JSON.parse JSON.stringify obj, visitor | ||
|
||
do serialize = (obj) -> | ||
switch typeof obj | ||
when 'boolean' then obj + '' | ||
|
||
when 'number' | ||
if isFinite obj | ||
obj + '' | ||
else # NaN, Infinity and -Infinity | ||
'null' | ||
|
||
when 'string' | ||
if obj.indexOf('\n') is -1 | ||
JSON.stringify obj | ||
else | ||
string = obj.replace tripleQuotesRE, "\\'''" | ||
string = newlineWrap indentLines string | ||
"'''#{ string }'''" | ||
|
||
when 'object' | ||
if obj is null | ||
'null' | ||
|
||
else if Array.isArray obj | ||
array = obj.map(serialize).join '\n' | ||
array = newlineWrap indentLines array | ||
"[#{ array }]" | ||
|
||
else | ||
keypairs = for key, val of obj | ||
key = JSON.stringify key unless key.match jsIdentifierRE | ||
val = serialize val | ||
"#{ key }: #{ val }" | ||
|
||
object = keypairs.join '\n' | ||
object = newlineWrap indentLines object | ||
"{#{ object }}" |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,122 @@ | ||
|
||
assert = require 'assertive' | ||
{ equal } = require 'assertive' | ||
|
||
CSON = require '../' | ||
cson = (obj, visitor, space = 2) -> CSON.stringify obj, visitor, space | ||
|
||
describe 'CSON.stringify', -> | ||
it 'works just like JSON.stringify', -> | ||
assert.equal '{"a":"b"}', CSON.stringify(a: 'b') | ||
it 'handles null', -> | ||
equal 'null', cson null | ||
|
||
it 'handles boolean values', -> | ||
equal 'true', cson true | ||
equal 'false', cson false | ||
|
||
it 'handles the empty object', -> | ||
equal '{}', cson {} | ||
|
||
it 'handles the empty array', -> | ||
equal '[]', cson [] | ||
|
||
it 'handles numbers', -> | ||
equal '0.42', cson 0.42 | ||
equal '42', cson 42 | ||
equal '1.2e+90', cson 1.2e+90 | ||
|
||
it 'handles single-line strings', -> | ||
equal '"hello!"', cson 'hello!' | ||
|
||
it 'handles multi-line strings', -> | ||
equal """ | ||
''' | ||
I am your average multi-line string, | ||
and I have a sneaky \\''' in here, too | ||
''' | ||
""", cson """ | ||
I am your average multi-line string, | ||
and I have a sneaky ''' in here, too | ||
""" | ||
|
||
it 'handles arrays', -> | ||
equal ''' | ||
[ | ||
[ | ||
1 | ||
] | ||
null | ||
[] | ||
{ | ||
a: "str" | ||
} | ||
] | ||
''', cson [ [1], null, [], a: 'str' ] | ||
|
||
it 'handles objects', -> | ||
equal ''' | ||
{ | ||
"": "empty" | ||
"non\\nidentifier": true | ||
default: false | ||
nested: { | ||
string: "too" | ||
} | ||
array: [ | ||
{} | ||
[] | ||
] | ||
} | ||
''', cson { | ||
'': 'empty' | ||
"non\nidentifier": true | ||
default: false | ||
nested: { | ||
string: 'too' | ||
} | ||
array: [ | ||
{} | ||
[] | ||
] | ||
} | ||
|
||
it 'handles NaN and +/-Infinity like JSON.stringify does', -> | ||
equal 'null', cson NaN | ||
equal 'null', cson +Infinity | ||
equal 'null', cson -Infinity | ||
|
||
it 'handles undefined like JSON.stringify does', -> | ||
equal undefined, cson undefined | ||
|
||
it 'handles functions like JSON.stringify does', -> | ||
equal undefined, cson -> | ||
|
||
it 'works just like JSON.stringify when asking for no indentation', -> | ||
equal '{"zeroed":0}', cson zeroed: 0, null, 0 | ||
equal '{"empty":""}', cson empty: '', null, '' | ||
|
||
it 'accepts no more than ten indentation steps, just like JSON.stringify', -> | ||
equal ''' | ||
{ | ||
"don't": "be silly, will'ya?" | ||
} | ||
''', cson {"don't": "be silly, will'ya?"}, null, Infinity | ||
|
||
it 'lets people that really want to indent with tabs', -> | ||
equal ''' | ||
{ | ||
\t\t"super-tabby": true | ||
} | ||
''', cson {'super-tabby': yes}, null, '\t\t' | ||
|
||
it 'is bug compatible with JSON.stringify for non-whitespace indention', -> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. chuckles That's kind of brilliant. :-D Shame the spec says truncate at 10 chars, ansi or not. :-) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, I originally had two blocks but that was too long. ^^ |
||
equal ''' | ||
{ | ||
ecma-262strange: true | ||
} | ||
''', cson {strange: yes}, null, 'ecma-262' | ||
|
||
it 'handles visitor functions', -> | ||
equal ''' | ||
{ | ||
keep: 1 | ||
} | ||
''', cson {filter: 'me', keep: 1}, (k, v) -> v unless typeof v is 'string' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I know you love diff'ability - would it be worth to make this serialize as
[\n]
? Not feeling strong either way.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I actually ran a little poll among peers (including a few as fond of comma-first json as I am), who all barfed on it. :-) I also searched around a bit, looking at implementations, and couldn't find any who did, so it might be safer for adoption if we don't either.
I'd be okay with either, but didn't feel like sticking out my chin to promote it, especially as there is some benefit in being able to quickly glean what values are, and a json object full of empty arrays and objects gets three times as compact and gleanable the current way.