Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JSON Patch format to remove an element from an array?

Tags:

I have the following JSON document, from which I want to remove the "roleId2" element from the "roles" field's array value:

{   "id" : 12345,   "firstName": "SomeFirstName",   "lastName": "SomeLastName",   "roles":["roleId1", "roleId2", "roleId3"] } 

How can I write a JSON Patch document to remove that element? Is the following expression valid?

{"op": "remove", "path":"/roles", "value": "roleId2"} 

Or, should it look like this (because the "roles" value in the document is an array)?

{"op": "remove", "path":"/roles", "value": ["roleId2"]} 

From reading RFC 6902, it is not clear to me which—if either—is correct. The RFC mentions the following behavior, but I'm not sure if it's relevant here.

If removing an element from an array, any elements above the specified index are shifted one position to the left.

like image 433
Niranjan Avatar asked Dec 12 '14 08:12

Niranjan


People also ask

What is JSON patching?

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.

What is merge patch JSON?

A JSON merge patch document describes changes to be made to a target JSON document using a syntax that closely mimics the document being modified.

What is path in patch request?

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.


2 Answers

The correct patch to remove item at index 1 from the array is:

{"op": "remove", "path": "/roles/1"} 

See working example at JSFiddle (using Fast-JSON-Patch)

like image 69
warpech Avatar answered Oct 09 '22 10:10

warpech


This is not supported by the RFC 6902. A possibile revision to the JSON-Patch format is being discussed, which may support value-based array operations.

like image 22
Petr Gotthard Avatar answered Oct 09 '22 09:10

Petr Gotthard