Sort an Object or package.json based on the well-known package.json keys
Installations
npm install sort-package-json
Developer Guide
Typescript
Yes
Module System
ESM
Node Version
20.18.1
NPM Version
10.8.2
Score
98.5
Supply Chain
99.6
Quality
88.2
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Languages
JavaScript (98.87%)
TypeScript (0.9%)
Shell (0.23%)
Developer
keithamus
Download Statistics
Total Downloads
208,727,112
Last Day
313,542
Last Week
1,549,330
Last Month
7,041,638
Last Year
81,997,107
GitHub Statistics
824 Stars
218 Commits
90 Forks
8 Watching
7 Branches
67 Contributors
Bundle Size
31.51 kB
Minified
10.04 kB
Minified + Gzipped
Package Meta Information
Latest Version
2.14.0
Package Id
sort-package-json@2.14.0
Unpacked Size
129.23 kB
Size
28.70 kB
File Count
9
NPM Version
10.8.2
Node Version
20.18.1
Publised On
15 Jan 2025
Total Downloads
Cumulative downloads
Total Downloads
208,727,112
Last day
-12.6%
313,542
Compared to previous day
Last week
-16.4%
1,549,330
Compared to previous week
Last month
-2.8%
7,041,638
Compared to previous month
Last year
67.6%
81,997,107
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
8
Sort Package.json
CLI
Run via npx (npm@5.2+ required)
1npx sort-package-json
Install
1npm install --global sort-package-json
Usage
1$ cd my-project 2$ cat package.json 3{ 4 "dependencies": { 5 "sort-package-json": "1.0.0", 6 "sort-object-keys": "1.0.0" 7 }, 8 "version": "1.0.0", 9 "name": "my-awesome-project" 10} 11 12$ npx sort-package-json 13package.json is sorted! 14 15Found 1 file. 161 file successfully sorted. 17 18$ cat package.json 19{ 20 "name": "my-awesome-project", 21 "version": "1.0.0", 22 "dependencies": { 23 "sort-object-keys": "1.0.0", 24 "sort-package-json": "1.0.0" 25 } 26}
CLI also supports multi file paths or glob
- so you can give it a bunch of package.json
file(s) to sort.
1$ sort-package-json "my-package/package.json" "other-package/package.json" 2 3$ sort-package-json "package.json" "packages/*/package.json" 4 5$ sort-package-json "package.json" "packages/*/package.json" --ignore "packages/one-package"
--check
flag
When you want to check if your files are sorted, you can run CLI with the --check
flag (or -c
). This will output a list of not sorted files, if any.
1$ sort-package-json "**/package.json" --check 2 3Found 5 files. 45 files were already sorted. 5 6$ sort-package-json "**/package.json" --check 7foo/package.json 8bar/package.json 9 10Found 5 files. 113 files were not sorted. 122 files were already sorted.
--quiet
flag
In order to silence any successful output, you can run CLI with the --quiet
flag (or -q
). This will stop the CLI from outputting if it runs successfully, but won't effect error messages and the exit code.
1$ sort-package-json "**/package.json" --check --quiet 2$ sort-package-json "**/package.json" --quiet
--stdin
flag
To read from stdin
and output the result to stdout
use the --stdin
flag.
1$ cat package.json | sort-package-json --stdin
This can, for instance, be used to generate a diff before changing package.json
.
1$ ( PKG="./package.json" ; cat "${PKG?}" | sort-package-json --stdin | diff "${PKG?}" - ; )
API
Install
1npm install --save-dev sort-package-json
Usage
1sortPackageJson(packageJson, options?)
Pass a JSON string, return a new sorted JSON string.
Pass a JSON object, return a new sorted JSON object.
1import sortPackageJson from 'sort-package-json' 2 3const packageJsonString = `{ 4 "dependencies": { 5 "sort-package-json": "1.0.0", 6 "sort-object-keys": "1.0.0" 7 }, 8 "version": "1.0.0", 9 "name": "my-awesome-project" 10}` 11 12console.log(sortPackageJson(packageJsonString)) 13/* => string: 14{ 15 "name": "my-awesome-project", 16 "version": "1.0.0", 17 "dependencies": { 18 "sort-object-keys": "1.0.0", 19 "sort-package-json": "1.0.0" 20 } 21} 22*/ 23 24const packageJsonObject = JSON.parse(packageJsonString) 25console.log(sortPackageJson(packageJsonObject)) 26/* => object: 27{ 28 name: 'my-awesome-project', 29 version: '1.0.0', 30 dependencies: { 31 'sort-object-keys': '1.0.0', 32 'sort-package-json': '1.0.0' 33 } 34} 35*/
options.sortOrder
Type: string[] | Function
Default: sortPackageJson.sortOrder
Custom ordering array or comparator function.
If an array, sort keys in ordering of options.sortOrder
.
Notice: fields not in this array, will still sort by defaultSortOrder
1const sorted = sortPackageJson(packageJsonObject, { 2 sortOrder: ['version'], 3}) 4 5console.log(Object.keys(sorted)) 6 7// -> [ 'version', 'name', 'dependencies' ] 8// ^^^^^^^^^^^^^^^^^^^^^^ 9// `name` and `dependencies` are sorted by defaultSortOrder
If a function, sort fields by Array#sort(options.sortOrder)
1const sorted = sortPackageJson(packageJsonObject, { 2 sortOrder(left, right) { 3 return left.localeCompare(right) 4 }, 5}) 6 7console.log(Object.keys(sorted)) 8 9// -> [ 'dependencies', 'name', 'version' ]
Related tools
Supported Libraries
- AVA
- Babel
- Browserify
- c8
- commitlint
- ESLint
- Husky
- Istanbul
- Jest
- lint-staged
- Mocha
- node-pre-gyp
- npm-package-json-lint
- oclif
- pnpm
- Prettier
- remark
- semantic-release
- stylelint
- Tap
- xojs
Alphabetically ordered.
Automatically Sort
The package.json file can be sorted automatically before committing.
1npm install husky lint-staged --save-dev 2npm pkg set scripts.prepare="husky install" 3npm run prepare 4npx husky add .husky/pre-commit "npx lint-staged"
Add the following to your package.json
file
1{ 2 "lint-staged": { 3 "package.json": "sort-package-json" 4 } 5}
See Husky and lint-staged for more information.
PFAQ: Potential Frequently Asked Questions
How does it sort?
It sorts using sort-object-keys
. It sorts using the well-known keys of a package.json. For the full list check the default rules. It sorts sub-keys too - sometimes by a well-known order, other times alphabetically. The initial order was derived from the package.json docs with a few extras added for good measure.
It doesn't sort X?
Cool. Send a PR! It might get denied if it is a specific vendor key of an unpopular project (e.g. "my-super-unknown-project"
). We sort keys like "browserify" because it is a project with millions of users. If your project has, say, over 100 users, then we'll add it. Sound fair?
Isn't this just like Project X?
Could be. I wanted this one because at the time of writing, nothing is:
- Zero config
- Able to be used in a library
- Quiet (i.e. not spitting out annoying log messages, when used in a library mode)
I would like this tool to be configurable with a config file or command line arguments.
The lack of configuration here is a feature, not a bug. The intent of this tool is that a user can open a package json and always expect to see keys in a particular order. If we add a configuration for this tool, then that promise is broken, as users will first need to look at the configuration for each project to learn the ways in which this tool will change the package.json
. The structure of the package.json
should always be predictable & deterministic from project to project. I think the reason why this project is well used is because it is not another "tool" you have to set up with yet another JSON file and more cruft in your project to support it. You run a command and it does what it says on the tin.
A lot of people who ask for configuration cite the use case that they simply don't like the given order that exists and want to make sweeping changes. To me this seems far better suited to simply making a fork of this project as then you can go far further than specifying configuration.
What is the order this package defaults to?
The default order is exported as a sortOrder
object.
Properties mentioned in the npm docs
name
version
private
description
keywords
homepage
bugs
repository
funding
license
author
contributors
main
browser
bin
man
directories
files
workspaces
scripts
config
dependencies
engines
os
cpu
Full list of recognized properties
$schema
name
displayName
version
private
description
categories
keywords
homepage
bugs
repository
funding
license
qna
author
maintainers
contributors
publisher
sideEffects
type
imports
exports
main
svelte
umd:main
jsdelivr
unpkg
module
source
jsnext:main
browser
react-native
types
typesVersions
typings
style
example
examplestyle
assets
bin
man
directories
files
workspaces
binary
scripts
betterScripts
contributes
activationEvents
husky
simple-git-hooks
pre-commit
commitlint
lint-staged
nano-staged
config
nodemonConfig
browserify
babel
browserslist
xo
prettier
eslintConfig
eslintIgnore
npmpkgjsonlint
npmPackageJsonLintConfig
npmpackagejsonlint
release
remarkConfig
stylelint
ava
jest
jest-junit
jest-stare
mocha
nyc
c8
tap
resolutions
dependencies
devDependencies
dependenciesMeta
peerDependencies
peerDependenciesMeta
optionalDependencies
bundledDependencies
bundleDependencies
extensionPack
extensionDependencies
flat
packageManager
engines
engineStrict
volta
languageName
os
cpu
preferGlobal
publishConfig
icon
badges
galleryBanner
preview
markdown
pnpm
What?! Why would you want to do this?!
Well, it's nice to have the keys of a package.json in a well sorted order. Almost everyone would agree having "name" at the top of a package.json is sensible (rather than sorted alphabetically or somewhere silly like the bottom), so why not the rest of the package.json?
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
packaging workflow detected
Details
- Info: Project packages its releases by way of GitHub Actions.: .github/workflows/release.yml:7
Reason
Found 24/26 approved changesets -- score normalized to 9
Reason
5 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 1
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/pr.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/keithamus/sort-package-json/pr.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/pr.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/keithamus/sort-package-json/pr.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/keithamus/sort-package-json/release.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/keithamus/sort-package-json/release.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/pr.yml:33
- Warn: npmCommand not pinned by hash: .github/workflows/release.yml:19
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 3 npmCommand dependencies pinned
Reason
9 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-rc47-6667-2j5j
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-f9xv-q969-pqx4
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/pr.yml:1
- Warn: no topLevel permission defined: .github/workflows/release.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 28 are checked with a SAST tool
Score
4.7
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More