#!/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;
      }
    },
    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 {
    return JSON.stringify(parser.parse(source),null,options.indent);
  } catch (e) {
    sys.puts(e);
    process.exit(1);
  }
}

function main (args) {
  var 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.pupts(parse(source));
    }
  } else {
    var stdin = process.openStdin();
    stdin.setEncoding('utf8');

    stdin.on('data', function (chunk) {
      source += chunk.toString('utf8');
    });
    stdin.on('end', function () {
      sys.puts(parse(source));
    });
  }
}

main(process.argv.slice(1));

@@ -479,24 +479,108 @@
    %7D%0A    %7D,%0A
+    sort : %7B%0A      string: '-s, --sort-keys',%0A      help: 'sort object keys'%0A    %7D,%0A
     inplace 
@@ -579,24 +579,24 @@
 inplace : %7B%0A
-
       string
@@ -852,50 +852,166 @@
     
-return JSON.stringify(parser.parse(source)
+var parsed = options.sort ?%0A                    sortObject(parser.parse(source)) :%0A                    parser.parse(source); %0A    return JSON.stringify(parsed
 ,nul
@@ -1387,17 +1387,16 @@
   sys.pu
-p
 ts(parse
@@ -1653,23 +1653,450 @@
     %7D);%0A
-
   %7D%0A%7D%0A%0A
+// from http://stackoverflow.com/questions/1359761/sorting-a-json-object-in-javascript%0Afunction sortObject(o) %7B%0A  if (Object.prototype.toString.call(o) != '%5Bobject Object%5D')%0A    return o;%0A  var sorted = %7B%7D,%0A  key, a = %5B%5D;%0A%0A  for (key in o) %7B%0A    if (o.hasOwnProperty(key)) %7B%0A      a.push(key);%0A    %7D%0A  %7D%0A%0A  a.sort();%0A%0A  for (key = 0; key %3C a.length; key++) %7B%0A    sorted%5Ba%5Bkey%5D%5D = sortObject(o%5Ba%5Bkey%5D%5D);%0A  %7D%0A  return sorted;%0A%7D%0A%0A
 main(pro

add option to sort object keys