Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
sort-package-json
Advanced tools
Sort an Object or package.json based on the well-known package.json keys
The sort-package-json npm package is a utility that automatically sorts the properties in package.json files according to a standard convention. This helps in maintaining consistency and readability in package.json files across different projects.
Sorting package.json
This feature sorts the keys in a package.json object. It takes an unsorted package.json object as input and returns a string with the keys sorted in a standard order.
const sortPackageJson = require('sort-package-json');
const sortedContent = sortPackageJson(JSON.stringify(packageJsonObject));
CLI Usage
sort-package-json can be used directly from the command line to sort the package.json file in the current directory. This is useful for quick formatting without writing any JavaScript code.
npx sort-package-json
API Usage
The package provides an API that can be used in Node.js scripts. This example reads a package.json file, sorts it, and then writes the sorted JSON back to the file.
const fs = require('fs');
const sortPackageJson = require('sort-package-json');
const packageJson = fs.readFileSync('package.json', 'utf8');
const sortedPackageJson = sortPackageJson(packageJson);
fs.writeFileSync('package.json', sortedPackageJson);
prettier-package-json is a package that formats package.json files. It sorts the keys and formats the JSON structure. It is similar to sort-package-json but also includes formatting capabilities that adhere to Prettier's styling rules.
fixpack is a package that not only sorts the keys in package.json but also validates and fixes missing or incorrect fields. It is more opinionated than sort-package-json and includes additional checks for common issues in package.json files.
npx sort-package-json
npm install --global sort-package-json
$ cd my-project
$ cat package.json
{
"dependencies": {
"sort-package-json": "1.0.0",
"sort-object-keys": "1.0.0"
},
"version": "1.0.0",
"name": "my-awesome-project"
}
$ npx sort-package-json
package.json is sorted!
Found 1 file.
1 file successfully sorted.
$ cat package.json
{
"name": "my-awesome-project",
"version": "1.0.0",
"dependencies": {
"sort-object-keys": "1.0.0",
"sort-package-json": "1.0.0"
}
}
CLI also supports multi file paths or glob
- so you can give it a bunch of package.json
file(s) to sort.
$ sort-package-json "my-package/package.json" "other-package/package.json"
$ sort-package-json "package.json" "packages/*/package.json"
$ sort-package-json "package.json" "packages/*/package.json" --ignore "packages/one-package"
--check
flagWhen 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.
$ sort-package-json "**/package.json" --check
Found 5 files.
5 files were already sorted.
$ sort-package-json "**/package.json" --check
foo/package.json
bar/package.json
Found 5 files.
3 files were not sorted.
2 files were already sorted.
--quiet
flagIn 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.
$ sort-package-json "**/package.json" --check --quiet
$ sort-package-json "**/package.json" --quiet
--stdin
flagTo read from stdin
and output the result to stdout
use the --stdin
flag.
$ cat package.json | sort-package-json --stdin
This can, for instance, be used to generate a diff before changing package.json
.
$ ( PKG="./package.json" ; cat "${PKG?}" | sort-package-json --stdin | diff "${PKG?}" - ; )
npm install --save-dev sort-package-json
sortPackageJson(packageJson, options?)
Pass a JSON string, return a new sorted JSON string.
Pass a JSON object, return a new sorted JSON object.
import sortPackageJson from 'sort-package-json'
const packageJsonString = `{
"dependencies": {
"sort-package-json": "1.0.0",
"sort-object-keys": "1.0.0"
},
"version": "1.0.0",
"name": "my-awesome-project"
}`
console.log(sortPackageJson(packageJsonString))
/* => string:
{
"name": "my-awesome-project",
"version": "1.0.0",
"dependencies": {
"sort-object-keys": "1.0.0",
"sort-package-json": "1.0.0"
}
}
*/
const packageJsonObject = JSON.parse(packageJsonString)
console.log(sortPackageJson(packageJsonObject))
/* => object:
{
name: 'my-awesome-project',
version: '1.0.0',
dependencies: {
'sort-object-keys': '1.0.0',
'sort-package-json': '1.0.0'
}
}
*/
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
const sorted = sortPackageJson(packageJsonObject, {
sortOrder: ['version'],
})
console.log(Object.keys(sorted))
// -> [ 'version', 'name', 'dependencies' ]
// ^^^^^^^^^^^^^^^^^^^^^^
// `name` and `dependencies` are sorted by defaultSortOrder
If a function, sort fields by Array#sort(options.sortOrder)
const sorted = sortPackageJson(packageJsonObject, {
sortOrder(left, right) {
return left.localeCompare(right)
},
})
console.log(Object.keys(sorted))
// -> [ 'dependencies', 'name', 'version' ]
Alphabetically ordered.
The package.json file can be sorted automatically before committing.
npm install husky lint-staged --save-dev
npm pkg set scripts.prepare="husky install"
npm run prepare
npx husky add .husky/pre-commit "npx lint-staged"
Add the following to your package.json
file
{
"lint-staged": {
"package.json": "sort-package-json"
}
}
See Husky and lint-staged for more information.
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.
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?
Could be. I wanted this one because at the time of writing, nothing is:
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.
The default order is exported as a sortOrder
object.
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
$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
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?
FAQs
Sort an Object or package.json based on the well-known package.json keys
The npm package sort-package-json receives a total of 932,944 weekly downloads. As such, sort-package-json popularity was classified as popular.
We found that sort-package-json demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.