Skip to content

Instantly share code, notes, and snippets.

@atk
Forked from 140bytes/LICENSE.txt
Created July 24, 2011 07:30
Show Gist options
  • Save atk/1102380 to your computer and use it in GitHub Desktop.
Save atk/1102380 to your computer and use it in GitHub Desktop.
JSONcleaner

JSONcleaner

Cleans up package.json files for our homepage - Removes comments, superflous commas at the end of objects and arrays and replaces single with double quotes and uses the client's JSON.stringify (or the stringifier at https://gist.github.com/1087317) to reformat the output.

Cannot fix erroneous quotations or unquoted object keys. If single quote strings contain unescaped double-quotes, this may result in errors (not a common use-case for the homepage).

function j(
a, // JSON data or full regex match
b, // undefined or singlequote string content
c // undefined or regex position
){
// is a position detected?
return c ?
// do we have a singlequote string match? return doublequoted, otherwise empty string
(b ? '"'+b+'"' : '') :
// not within regexp: Use JSON.stringify/.parse to reformat
JSON.stringify(JSON.parse(
// use regex to clear comments and detect singlequoted strings
a.replace(/\s*\/\/.*?\n|\s*\/\*.*?\*\/|,(?=\s*[\]}])|'(.*?)'/g,j)
))
}
function j(a,b,c){return c?(b?'"'+b+'"':''):JSON.stringify(JSON.parse(a.replace(/\s*\/\/.*?\n|\s*\/\*.*?\*\/|,(?=\s*[\]}])|'(.*?)'/g,j)))}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Alex Kloss <[email protected]>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "JSONcleaner",
"description": "Cleans Comments and superfluous commas of package.json resources",
"keywords": [
"JSON",
"clean",
"reformat"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>{"test":["finished","very successfully"]}</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var testdata = " { // rather difficult\n 'test': [ 'finished',\n /* all but */ 'very successfully', ], }";
var myFunction = function j(a,b,c){return c?(b?'"'+b+'"':''):JSON.stringify(JSON.parse(a.replace(/\s*\/\/.*?\n|\s*\/\*.*?\*\/|,(?=\s*[\]}])|'(.*?)'/g,j)))};
document.getElementById( "ret" ).innerHTML = myFunction(testdata)
</script>
@jed
Copy link

jed commented Jul 24, 2011

you should rethink the use of eval... can't use it in production with that.

@atk
Copy link
Author

atk commented Jul 24, 2011

Had problems with JSON.parse, alas. Am working on a better solution.

@atk
Copy link
Author

atk commented Jul 24, 2011

@jed , I think I nailed it.

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