Add multiple values to array in single JSON Patch operation?
Asked Answered
B

1

9

I have a json object like this:

{
    "content" : [
        {
            "id" : 54
            "foo" : "bar"
        },
        {
            "id" : 43
            "foo" : "bar"
        },
        {
            "id" : 76
            "foo" : "bar"
        }
    ]
}

If I want to add multiple items to the content array (order doesn't matter) can I add to it with a json patch with a single line/ operation with something like this?

{ "op": "add", "path": "/content/-", "value": [
        {
            "id" : 34
            "foo" : "bar"
        },
        {
            "id" : 23
            "foo" : "bar"
        },
        {
            "id" : 87
            "foo" : "bar"
        }
    ] 
}

Or do I have to do an additional line for each object I want to add?

EDIT: To be clear I want to append, not replace the content.

Barren answered 21/1, 2020 at 21:56 Comment(2)
I have the feeling you are not sure what you want to do. why not: ``` { "op":"add","path":{"content":[]}} or { "op":"add","path":{"content": { "values": []}}} ```Tatary
Won't that delete the existing items stored there? To be clear I want to append not replace.Barren
K
1

Unfortunately, this seems not (yet?) possible... as the Json Patch specification states :

https://www.rfc-editor.org/rfc/rfc6902#section-4.1

The "add" operation performs one of the following functions, depending upon what the target location references:

  • If the target location specifies an array index, a new value is inserted into the array at the specified index.

  • If the target location specifies an object member that does not already exist, a new member is added to the object.

  • If the target location specifies an object member that does exist, that member's value is replaced.

Kelter answered 8/4, 2021 at 15:33 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.