edit-package-json0.5.1
Quick Take
import { strict as assert } from "assert";
import { set, del } from "edit-package-json";
// edit JSON as string
assert.equal(
set(
`{
"name": "test",
"dependencies": {
"ranges-apply": "^2.0.0",
"string-left-right": "^2.3.30"
},
"devDependencies": {}
}`,
"dependencies.ranges-apply", // path to amend
"^3.2.2" // new value
),
`{
"name": "test",
"dependencies": {
"ranges-apply": "^3.2.2",
"string-left-right": "^2.3.30"
},
"devDependencies": {}
}`
);
// edit from JSON string
assert.equal(
del(
`{
"name": "test",
"dependencies": {
"ranges-apply": "^2.0.0",
"string-left-right": "^2.3.30"
},
"devDependencies": {}
}`,
"devDependencies" // path to delete
),
`{
"name": "test",
"dependencies": {
"ranges-apply": "^2.0.0",
"string-left-right": "^2.3.30"
}
}`
);
Examples
Purpose
Edit JSON contents as strings to guarantee the formatting will be intact.
API uses object-path notation to set values on any (for now, only already-existing) paths in JSON.
It's powering the update-versions
CLI.
API
There are two methods: set()
and del()
:
.set()
set(source, path, val)
Input argument | Type | Obligatory? | Description |
---|---|---|---|
str |
String | yes | JSON file contents |
path |
String | yes | Desired EXISTING path in the object, must follow object-path notation |
valToInsert |
Whatever | yes | What to insert at the given path |
You can't create new paths, only amend existing-ones.
Output
An amended string is returned.
To repeat, set()
can't create new paths yet, it's still in a baby state. set()
can only edit existing paths in JSON.
.del()
del(source, path)
Input argument | Type | Obligatory? | Description |
---|---|---|---|
str |
String | yes | JSON file contents |
path |
String | yes | Desired path in the object to delete, must follow object-path notation |
Output
An amended string is returned.
Testing
Besides regular unit tests, we went great lengths to ensure this program works as intended. We took all 119 package.json
's in this monorepo, then took every single leaf path in every package.json and amended and deleted it two ways:
- editing it directly, using this program, string-in, string-out
- editing using
object-path
, plain-object-in, plain-object-out, then stringify
Every single path edit matched! By the way, we ended up with 13,338 asserts.
See the source of the test file .
Changelog
See it in the monorepo , on GitHub.
Contributing
To report bugs or request features or assistance, raise an issue on GitHub .
Any code contributions welcome! All Pull Requests will be dealt promptly.
Licence
Copyright © 2010–2021 Roy Revelt and other contributors
Related packages:
indexOf
but returns array and counts per-grapheme
console.log
s in JS code