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

27.2k Views Asked by At

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.

2

There are 2 best solutions below

16
On

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)

5
On

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.