4 Commits

Author SHA1 Message Date
Zach Carter
280ccc5121 version 1.1.0 2011-06-01 17:56:38 -04:00
Zach Carter
f08f1b245f add option to sort object keys 2011-06-01 17:55:58 -04:00
Zach Carter
7d7e4b499f allow inplace overwrite 2011-06-01 17:42:36 -04:00
Zach Carter
26d697c45f Add nomnom for option parsing. Allow indentation option" 2011-06-01 17:24:24 -04:00
2 changed files with 69 additions and 7 deletions

View File

@@ -1,11 +1,45 @@
#!/usr/bin/env node
var sys = require("sys");
var fs = require("fs");
var parser = require("./jsonlint").parser;
var options = require("nomnom")
.scriptName("jsonlint")
.opts({
file: {
position: 0,
help: "file to parse; otherwise uses stdin"
},
version: {
string: '-v, --version',
help: 'print version and exit',
callback: function() {
return JSON.parse(fs.readFileSync(__dirname + "/../package.json", "utf8")).version;
}
},
sort : {
string: '-s, --sort-keys',
help: 'sort object keys'
},
inplace : {
string: '-i, --in-place',
help: 'overwrite the file'
},
indent : {
string: '-t CHAR, --indent CHAR',
default: " ",
help: 'character(s) to use for indentation'
}
})
.parseArgs();
function parse (source) {
try {
sys.puts(JSON.stringify(parser.parse(source),null," "));
var parsed = options.sort ?
sortObject(parser.parse(source)) :
parser.parse(source);
return JSON.stringify(parsed,null,options.indent);
} catch (e) {
sys.puts(e);
process.exit(1);
@@ -14,9 +48,14 @@ function parse (source) {
function main (args) {
var source = '';
if (args[1]) {
source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), "utf8");
parse(source);
if (options.file) {
var path = require('path').join(process.cwd(), options.file);
source = fs.readFileSync(path, "utf8");
if (options.inplace) {
fs.writeSync(fs.openSync(path,'w+'), parse(source), 0, "utf8");
} else {
sys.puts(parse(source));
}
} else {
var stdin = process.openStdin();
stdin.setEncoding('utf8');
@@ -25,9 +64,30 @@ function main (args) {
source += chunk.toString('utf8');
});
stdin.on('end', function () {
parse(source);
sys.puts(parse(source));
});
}
}
// from http://stackoverflow.com/questions/1359761/sorting-a-json-object-in-javascript
function sortObject(o) {
if (Object.prototype.toString.call(o) != '[object Object]')
return o;
var sorted = {},
key, a = [];
for (key in o) {
if (o.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = sortObject(o[a[key]]);
}
return sorted;
}
main(process.argv.slice(1));

View File

@@ -8,7 +8,7 @@
"lint",
"jsonlint"
],
"version": "1.0.1",
"version": "1.1.0",
"preferGlobal": true,
"repository": {
"type": "git",
@@ -24,7 +24,9 @@
"engines": {
"node": "0.4 || 0.5"
},
"dependencies": {},
"dependencies": {
"nomnom": ">= 0.4.3"
},
"devDependencies": {
"test": "*",
"jison": "*",