How to use the fast-json-patch.compare function in fast-json-patch

To help you get started, we’ve selected a few fast-json-patch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github caohanyang / json_diff_rfc6902 / tests / diff.js View on Github external
var f_old = require(root + "old.json");
  var app_old = JSON.parse(JSON.stringify(f_old));
  var old_ori = JSON.parse(JSON.stringify(f_old));
  var f_new = require(root + "new.json");

  // var exp_patch = require(root + "expected.json");
  console.time("jdr-diff");
  // var jdr_patch = jdr.diff(f_old, f_new);  , HASH_ID: "title"
  var jdr_patch = jdr.diff(f_old, f_new, {OBJ_COM: true, ARR_COM: true});
  console.timeEnd("jdr-diff");

  console.time("jiff-diff");
  var jiff_patch = jiff.diff(f_old, f_new, jiff_options);
  console.timeEnd("jiff-diff");
  console.time("fjp-diff");
  var fjp_patch = fjp.compare(f_old, f_new);
  console.timeEnd("fjp-diff");
  console.time("rfc6902");
  var rfc6902_patch = rfc6902.createPatch(f_old, f_new);
  console.timeEnd("rfc6902");
  console.time("json8");
  var json8_patch = json8.diff(f_old, f_new);
  console.timeEnd("json8");

  // Use fjp to apply the patch fjp_patch jdr_patch jiff_patch
  fjp.apply(f_old, fjp_patch);

  jdr.apply(app_old, jdr_patch);

  fs.writeFile(root + "jdr_patch.json", JSON.stringify(jdr_patch, null, 2));
  fs.writeFile(root + "fjp_patch.json", JSON.stringify(fjp_patch, null, 2));
  fs.writeFile(root + "jiff_patch.json", JSON.stringify(jiff_patch, null, 2));
github EUDAT-B2SHARE / b2share / webui / src / components / editrecord.jsx View on Github external
updateRecord(event) {
        event.preventDefault();
        const errors = this.findValidationErrors();
        if (this.state.fileState !== 'done' || pairs(errors).length > 0) {
            this.setState({errors});
            return;
        }
        const original = this.props.record.get('metadata').toJS();
        const updated = this.state.record.toJS();
        const patch = compare(original, updated);
        if (!patch || !patch.length) {
            this.setState({dirty:false});
            return;
        }
        const afterPatch = (record) => {
            if (this.props.isDraft && !this.isForPublication()) {
                this.props.refreshCache();
                // TODO(edima): when a draft is publised, clean the state of
                // records in versioned chain, to trigger a refetch of
                // versioning data
                this.setState({dirty:false, waitingForServer: false});
                notifications.clearAll();
            } else {
                browser.gotoRecord(record.id);
            }
        }
github DefinitelyTyped / DefinitelyTyped / types / fast-json-patch / fast-json-patch-tests.ts View on Github external
{ op: "replace", path: "/firstName", value: "Joachim" },
  { op: "add", path: "/lastName", value: "Wester" },
  { op: "add", path: "/contactDetails/phoneNumbers/0", value: { number: "555-123" } }
];
jsonpatch.apply(myobj, patches);

var myobj2 = { firstName: "Joachim", lastName: "Wester", contactDetails: { phoneNumbers: [{ number: "555-123" }] } };
var observer = jsonpatch.observe(myobj2);
myobj2.firstName = "Albert";
myobj2.contactDetails.phoneNumbers[0].number = "123";
myobj2.contactDetails.phoneNumbers.push({ number: "456" });
var patches2 = jsonpatch.generate(observer);

var objA = { user: { firstName: "Albert", lastName: "Einstein" } };
var objB = { user: { firstName: "Albert", lastName: "Collins" } };
var diff = jsonpatch.compare(objA, objB);

var obj = { user: { firstName: "Albert" } };
var patches3 = [{ op: "replace", path: "/user/firstName", value: "Albert" }, { op: "replace", path: "/user/lastName", value: "Einstein" }];
var errors = jsonpatch.validate(patches, obj);
if (errors.length === 0) {
  //there are no errors!
} else {
  for (var i = 0; i < errors.length; i++) {
    if (!errors[i]) {
      console.log("Valid patch at index", i, patches[i]);
    } else {
      console.error("Invalid patch at index", i, errors[i], patches[i]);
    }
  }
}
github colyseus / colyseus / test / benchmark / patch.js View on Github external
suite.add('using json', function() {
  for (var i=0; i<4; i++) {
    obj2.objs[0].hp--;
    obj2.objs[2].hp--;
    obj2.teams[i].score++;
    var newState = JSON.parse(JSON.stringify(obj2.toJSON()))
    var diff = msgpack.encode( jsonpatch.compare(state2, newState) )
    state2 = newState
  }
  this.bytes = diff.length;
});
github ovh / cds / ui / src / app / views / pipeline / show / audit / pipeline.audit.component.ts View on Github external
this.indexSelected = i;
        let indexToCompare = (this.currentPage - 1) * this.nbElementsByPage + i;

        let pipFrom = cloneDeep(this.audits[indexToCompare].pipeline);
        let pipTo: Pipeline;
        if (indexToCompare === 0) {
            pipTo = cloneDeep(this.pipeline);
        } else {
            pipTo = cloneDeep(this.audits[indexToCompare - 1].pipeline);
        }

        pipFrom = this.cleanPipeline(pipFrom);
        pipTo = this.cleanPipeline(pipTo);

        this.currentCompare = new Array();
        compare(pipFrom, pipTo).forEach(c => {
            let diff = new PipelineAuditDiff();
            let path = c.path;
            let pathSplitted = path.split('/').filter(p => p !== '');

            switch (this.audits[indexToCompare].action) {
                case 'addStage':
                    diff = this.getAddStageDiff(pathSplitted, pipTo);
                    break;
                case 'updateStage':
                    diff = this.getUpdateStageDiff(pathSplitted, pipTo, pipFrom);
                    break;
                case 'deleteStage':
                    diff = this.getDeleteStageDiff(pathSplitted, pipFrom);
                    break;
                case 'addJob':
                    diff = this.getAddJobDiff(pathSplitted, pipTo);
github jessedc / ajv-cli / commands / validate.js View on Github external
function validateDataFile(file) {
        var data = util.openFile(file, 'data file ' + file);
        var original;
        if (argv.changes) original = JSON.parse(JSON.stringify(data));
        var validData = validate(data);

        if (validData) {
            console.log(file, 'valid');
            if (argv.changes) {
                var patch = jsonPatch.compare(original, data);
                if (patch.length == 0) {
                    console.log('no changes');
                } else {
                    console.log('changes:');
                    console.log(util.logJSON(argv.changes, patch));
                }
            }
        } else {
            allValid = false;
            console.error(file, 'invalid');
            console.error(util.logJSON(argv.errors, validate.errors, ajv));
        }
    }
}
github yahoo / elide-js / lib / datastores / memorydatastore.js View on Github external
commit(_) {
    let willReject = false;

    if (!this._upstream) {
      return this._promise.reject(new Error(ERROR_NO_UPSTREAM));
    }

    let patches = jsonpatch.compare(this._snapshot, this._data);

    return this._upstream.commit(patches).then((upstreamResults) => {
      if (upstreamResults) {
        for (let i = 0; i < upstreamResults.length; i++) {
          let result = upstreamResults[i];

          let type = result.type;
          let data = result.data;
          let curId = data.id;
          let lastId = result.oldId;

          if (lastId && lastId !== curId) {
            this._meta[type][lastId] = curId;
            delete this._data[type][lastId];
          }
github Soluto / tweek / e2e / integration / spec / gateway / v2.spec.js View on Github external
object: 'repo.keys/*',
          action: 'write',
          effect: 'allow',
        },
      ],
    };

    const patch = jsonpatch.compare(currentPolicy, newPolicy);
    await client
      .patch('/api/v2/policies?author.name=test&author.email=test@soluto.com')
      .send(patch)
      .expect(200);

    await client.get('/api/v2/policies').expect(200, newPolicy);

    const cleanup = jsonpatch.compare(newPolicy, currentPolicy);
    await client
      .patch('/api/v2/policies?author.name=test&author.email=test@soluto.com')
      .send(cleanup)
      .expect(200);
  });
});
github Azure-Samples / digital-twins-explorer / client / src / components / PropertyInspectorComponent / PropertyInspectorComponent.js View on Github external
onSave = async () => {
    const { changed, selection } = this.state;
    if (changed) {
      const deltaFromDefaults = compare(this.original, this.updated);
      const deltaFromOriginal = compare(selection, this.updated);
      const delta = deltaFromOriginal.filter(x => deltaFromDefaults.some(y => y.path === x.path));
      this.setState({ patch: delta });

      const patch = JSON.stringify(delta, null, 2);
      print("*** PI Changes:", "info");
      print(patch, "info");
      if (patch.length > 0) {
        await this.patchTwin(delta);
      }

      this.showModal();
      this.setState({ changed: false });
    }
  }