edit-package-json examples

Table of Contents

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"
  }
}`
);

Minimal example, del()

import { strict as assert } from "assert";
import { del } from "edit-package-json";

// edit JSON as string
assert.equal(
  del(
    `{
  "a": "b",
  "c": "d"
}`,
    "c" // path to delete
  ),
  `{
  "a": "b"
}`
);

Minimal example, set()

import { strict as assert } from "assert";
import { set } from "edit-package-json";

// edit JSON as string
assert.equal(
  set(
    `{
  "a": "b",
  "c": {
    "d": "e"
  }
}`,
    "c.d", // path
    "x" // value to put
  ),
  `{
  "a": "b",
  "c": {
    "d": "x"
  }
}`
);