Thomas K
Thomas K

Reputation: 1117

RFC 7396 - JSON Merge Patch - Updating objects in a list

The RFC 7396 states:

If the patch is anything other than an object, the result will always be to replace the entire target with the entire patch. Also, it is not possible to patch part of a target that is not an object, such as to replace just some of the values in an array.

For example, if I have this document :

{
  "id": 1,
  "brand_name": "BMW",
  "cars": [{
    "id": 2,
    "model": "S1",
    "cost": 10000
  }]
}

It is my understanding I can't partially update the car with the id #2 in order to update the cost for example:

{
  "id": 1,
  "cars": [{
    "id": 2,
    "cost": 20000
  }]
}

(the idea here is to do not modify the model, just the cost. The ids are present just for the reconciliation)

Is that correct ?

If so, why couldn't we apply this algorithm to deal with lists:

Is that realistic ?

Upvotes: 0

Views: 3118

Answers (2)

okolnost
okolnost

Reputation: 113

Summary

You can achieve what you want with RFC 7396.

The spec is a bit vague.

But their example shows exactly what you want.

RFC 7396 Example

Given the following example JSON document:

   {
     "title": "Goodbye!",
     "author" : {
       "givenName" : "John",
       "familyName" : "Doe"
     },
     "tags":[ "example", "sample" ],
     "content": "This will be unchanged"
   }

PATCH /my/resource HTTP/1.1
Host: example.org
Content-Type: application/merge-patch+json

   {
     "title": "Hello!",
     "phoneNumber": "+01-123-456-7890",
     "author": {
       "familyName": null
     },
     "tags": [ "example" ]
   }

The resulting JSON document would be:

   {
     "title": "Hello!",
     "author" : {
       "givenName" : "John"
     },
     "tags": [ "example" ],
     "content": "This will be unchanged",
     "phoneNumber": "+01-123-456-7890"
   }

Conclusions

As you can see, the nested object author has been updated by deleting attribute familyName, but it retained attribute givenName even though that was not included in the patch document.

For me that clearly shows that you do not need to provide nested attributes or objects that you do not want to change and they should be retained.

Consequently, if you want to delete them, you need to include them with null value.

Note that the authors of spec managed to get most of the possible changes into one example (well done):

  • change value of existing attribute title
  • change object author
  • delete nested attribute familyName
  • keep unchanged nested attribute givenName
  • change array value of tags
  • keep unchanged attribute content
  • add attribute phoneNumber

Upvotes: 0

Evert
Evert

Reputation: 99728

The way I read the the paragraph you sent, I would say.. no you are not able to do this. My understanding is that RFC 7396 is intended as a very simple no-fuss patch format.

If you want something with more features, consider using RFC 6902 instead.

Upvotes: 1

Related Questions