1

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.

1 Answer 1

4

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"}]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.