zaach / jsonlint

A JSON parser and validator with a CLI.
http://zaach.github.com/jsonlint/
1.93k stars 417 forks source link

Sort keys but not top-level keys #143

Open vezaynk opened 1 year ago

vezaynk commented 1 year ago

A package.json looks like this:

{
  "name": "...",
  "dependencies": {
     "a": "...",
     "b": "..."
  }
}

I want to keep the order of name and dependencies, but want to make sure that the list of dependencies are sorted. I think a good approach for this would be to let the --sort-keys flag accept a number, which is the minimum depth at which it begins sorting.

 npx jsonlint -s 1 -i -q package.json
vezaynk commented 1 year ago

I implemented this for myself.

Here is the diff:

diff --git a/node_modules/jsonlint/lib/cli.js b/node_modules/jsonlint/lib/cli.js
index 981c15f..7c7894d 100755
--- a/node_modules/jsonlint/lib/cli.js
+++ b/node_modules/jsonlint/lib/cli.js
@@ -21,10 +21,10 @@ var options = require("nomnom")
         return require("../package").version;
       }
     },
-    sort : {
-      flag : true,
-      string: '-s, --sort-keys',
-      help: 'sort object keys'
+    sort: {
+      string: '-s, --sort-keys [depth]',
+      help: 'sort object keys',
+      type: 'number'
     },
     inplace : {
       flag : true,
@@ -77,8 +77,8 @@ function parse (source) {
       formatted;

   try {
-    parsed = options.sort ?
-      sortObject(parser.parse(source)) :
+    parsed = typeof options.sort === 'number' ?
+      sortObject(parser.parse(source), options.sort) :
       parser.parse(source);

     if (options.validate) {
@@ -152,9 +152,9 @@ function main (args) {
 }

 // from http://stackoverflow.com/questions/1359761/sorting-a-json-object-in-javascript
-function sortObject(o) {
+function sortObject(o, depth) {
   if (Array.isArray(o)) {
-    return o.map(sortObject);
+    return o.map(k => sortObject(k, depth-1));
   } else if (Object.prototype.toString.call(o) !== '[object Object]') {
     return o;
   }
@@ -168,10 +168,10 @@ function sortObject(o) {
     }
   }

-  a.sort();
+  if (depth <= 0) a.sort();

   for (key = 0; key < a.length; key++) {
-    sorted[a[key]] = sortObject(o[a[key]]);
+    sorted[a[key]] = sortObject(o[a[key]], depth-1);
   }
   return sorted;
 }