Starcounter-Jack / JSON-Patch

Lean and mean Javascript implementation of the JSON-Patch standard (RFC 6902). Update JSON documents using delta patches.
MIT License
1.79k stars 215 forks source link

Possible to construct JSON object from path + value? #254

Closed Jas-SinghFSU closed 4 years ago

Jas-SinghFSU commented 4 years ago

Hello, after running a compare operation on two documents, I get a list of patches. Is it possible to take these patches, for example:

const documentA = { user: [{ name: { first: 'Bob' } }] };
const documentB = { user: [{ name: { first: 'Bob', second: 'Saget' } }] };

const jsonDiff = compare(documentA, documentB);

/*
jsonDiff = { op: 'add', path: '/user/0/name/second', value: 'Saget' }
*/

Then build this patch into a JSON object like this?

{ 
  user: [
    { 
      name: { second: 'Saget' } 
    }
  ] 
}
Starcounter-Jack commented 4 years ago

JSON-Patch was not intended to create an object like the one that you suggested. However, the JSON pointer (the path) contains enough information to reconstruct an object void of the non-changed properties and objects. I suggest you loop through the patches and, for each patch, loop through the path while reconstructing the objects and arrays recursively. Whenever you encounter an integer, you now that there is an array and otherwise, you know there is an object with a property.