jsonsql-serversql-server-json

How to replace complete object within JSON Object in Sql server


I am trying to modify existing json in sql and adding a new property in each object in array.

My json is as given below

{"Key":"Employee", "Data":[{"id": "1", "value": "Vogel"},{ "id": "2", "value": "Vogel"}]

Now I am trying to add a new property in each object inside Data property(Like IsDeleted :False).

Can we iterate each object inside a particular property which is an array in itself and add property in each object.


Solution

  • One possible approach is to convert $.Data part of your JSON string to table with OPENJSON(), SELECT rows with new isDeleted column as JSON and modify original JSON:

    DECLARE @json nvarchar(max)
    SET @json = N'
        {
        "Key": "Employee", 
        "Data": [
            {"id": "1", "value": "Vogel"},
            {"id": "2", "value": "Vogel"}
        ]
        }';
    
    SELECT @json = JSON_MODIFY(
       @json,
       '$.Data',
       (
       SELECT items.[id], items.[value], 'False' AS [isDeleted]
       FROM OPENJSON(JSON_QUERY(@json, '$.Data')) 
       WITH (
          [id] nvarchar(10),
          [value] nvarchar(100)  
       ) AS items
       FOR JSON PATH
       )
    )   
    

    Output:

    {
        "Key": "Employee", 
        "Data": [{"id":"1","value":"Vogel","isDeleted":"False"},{"id":"2","value":"Vogel","isDeleted":"False"}]
    }