UNPKG

json8-patch

Version:
40 lines (31 loc) 1.05 kB
"use strict"; const ooPointer = require("json8-pointer"); const decode = ooPointer.decode; const walk = require("./walk"); /** * @typedef OperationResult * @type Object * @property {Any} doc - The patched document * @property {Array} previous - The previous/replaced value if any */ /** * Replace the value at the JSON Pointer location * http://tools.ietf.org/html/rfc6902#section-4.3 * * @param {Any} doc - JSON document * @param {String|Array} path - JSON Pointer string or tokens patch * @param {String} value - JSON object to replace with * @return {OperationResult} */ module.exports = function replace(doc, path, value) { const tokens = decode(path); // replaces the document if (tokens.length === 0) return { doc: value, previous: doc }; const r = walk(doc, tokens); const token = r[0]; const parent = r[1]; const previous = parent[token]; if (previous === undefined) throw new Error("Location not found"); parent[token] = value; return { doc: doc, previous: previous }; };