Monday, April 19, 2021

Partial JSON Update Format (JSON PATCH)


     

      JSON is a quite common format for data in these days. NoSQL databases save data in JSON format. Even Relational Databases like SQL Server give you option to save or retrieve data in JSON format. When we need to update a property in a JSON document, we need to update the whole JSON document. This can be a problem specially if document size is larger. This is where JSON Patch feature comes in. JSON Patch is a format that let you update JSON document partially. 

     You can do more than updating a property. You can add, remove, replace, move, or test a value by using this format. Let's look at its details by using the following JSON document as the source.


     To send a partial JSON update request, we need to use the following format. We need send this JSON document to the source. Before you tried this, first you need to be sure that your source supports this format. For example, Azure Cosmos DB does not support this yet. Cosmos DB Team started to work on this request. You can see the details of this work from this link for Azure Cosmos DB


     If I want to update the topics of my document, and let's say I want to add another item to the array. I can make the following request to update this document partially.


     First thing you need to know about this request is the "-" character, it specifies that the value will added to the end of the array. If you like to add the value another position, you can specify the index of the location. Here is the result of this request.


     Following example shows you how to remove an item from the array.



Result

Replacing an item request

Result

You can move items by using the move operation. This operation runs the remove operation first then runs the add operation to accomplish move operation.



Result

You can use the copy operation to copy an item from one location another location without removing it.


Result

Test operation is interesting, For Test operation to be successful, data type and value must match the destination. Following request's response will be success.


1 comment:

  1. Nice!
    Wouldn't the op test path need to be something like /Owner/Name to get a success response?

    ReplyDelete