1

例如,我想从数组中删除子元素

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

我需要一个补丁来删除所有ID,这样我就可以做这样的事情

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

但是有没有办法指定通配符来选择数组中的所有 id 元素

4

1 回答 1

1

我一直在查看JSON 补丁草稿,但没有找到任何关于正则表达式的信息。一种解决方案是使用一些JSON解析工具来创建它,例如jqpython-json-patch。第一个删除所有id键,第二个从差异创建补丁,使用如下:

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

它产生:

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

还使用该jsonpatch工具来应用补丁,它似乎生成了正确的输出,例如:

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

它产生:

{"employees": [{"name": "name1"}, {"name": "name2"}, {"name": "name3"}]}
于 2015-07-03T13:35:10.130 回答