Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsonpatch all elements in array

The below post led me to evaluate using jasonpatch for json to json transformation:

JSON to JSON transformer

The project can be found here:

https://github.com/bruth/jsonpatch-js

I am currently trying to change the name of all elements in an array and am not seeing how this is possible. My current attempt is:

var transformations = [
{ op: 'move', from:'/hits/1/_id', path: '/hits/1/pizza'}
];

This swaps out the first element but how do I do a "*" card type operation? Something like:

var transformations = [
{ op: 'move', from:'/hits/*/_id', path: '/hits/*/pizza'}
];

I could see possibly calling the transformation N times for each element but that seems like a hack.

like image 497
Ryan R. Avatar asked Apr 16 '13 23:04

Ryan R.


People also ask

When should I use JSON Patch?

JSON Patch is a format for describing changes to a JSON document. It can be used to avoid sending a whole document when only a part has changed. When used in combination with the HTTP PATCH method, it allows partial updates for HTTP APIs in a standards compliant way. The patch documents are themselves JSON documents.

What is path in JSON Patch?

The path member is a JSON Pointer that determines a location within the JSON document to modify. 1. { "op": "add", "path": "/player/name" } The remaining elements of a JSON Patch operation depend on the particular operation being performed.

What is application JSON Patch JSON?

JSON Patch is a web standard format for describing changes in a JSON document. It is meant to be used together with HTTP Patch which allows for the modification of existing HTTP resources. The JSON Patch media type is application/json-patch+json . JSON Patch. Filename extension.

What is a JSON Patch document?

JSON Patch is a format for specifying updates to be applied to a resource. A JSON Patch document has an array of operations. Each operation identifies a particular type of change. Examples of such changes include adding an array element or replacing a property value.


1 Answers

Ended up using an approach where I wrapped the call to apply in a loop:

 for(i=0;i<json.hits.length;i++) {
    var transformations = [{ op: 'move', from:'/hits/'+i+'/_id', path:'/hits/'+i+'/pizza'}];
    var result = jsonpatch.apply(json,transformations);             
 }

Maybe jsonpatch could use a wildcard feature?

like image 101
Ryan R. Avatar answered Sep 29 '22 16:09

Ryan R.