Skip to content
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

Sort keys but not top-level keys #143

Open
vezaynk opened this issue Feb 7, 2023 · 1 comment
Open

Sort keys but not top-level keys #143

vezaynk opened this issue Feb 7, 2023 · 1 comment

Comments

@vezaynk
Copy link

vezaynk commented Feb 7, 2023

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
Copy link
Author

vezaynk commented Feb 7, 2023

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;
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant