Json Patch removing sub elements in an array

3.5k Views Asked by At

I want to remove sub elements from an array for example

{
    "employees": [
        {
            "name": "name1",
            "id": "id1"
        },
        {
            "name": "name2",
            "id": "id2"
        },
        {
            "name": "name3",
            "id": "id3"
        }
    ]
}

And i need a patch to remove all ids so i can do something like this

[{ "op": "remove", "path": "/employees/0/id"},
{ "op": "remove", "path": "/employees/1/id"},
{ "op": "remove", "path": "/employees/2/id"}]

But is there any way to specify wildcard to select all id elements in an array

1

There are 1 best solutions below

0
On BEST ANSWER

I've been looking at the JSON patch draft but didn't find anything about regular expressions. One solution is to use some JSON parse tools to create it, like jq and python-json-patch. The first one removes all id keys, and the second one creates a patch from a diff, used like:

jq 'del(.employees[].id)' jsonfile | jsondiff jsonfile -

It yields:

[{"op": "replace", "path": "/employees/2", "value": {"name": "name3"}}, 
 {"op": "replace", "path": "/employees/1", "value": {"name": "name2"}}, 
 {"op": "replace", "path": "/employees/0", "value": {"name": "name1"}}]

Using also the jsonpatch tool to apply the patch, it seems to generate a correct output, like:

jq 'del(.employees[].id)' jsonfile | jsondiff jsonfile - | jsonpatch jsonfile -

It yields:

{"employees": [{"name": "name1"}, {"name": "name2"}, {"name": "name3"}]}