Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete an item from JSON array in SQL Server

How can I delete an item from JSON array in SQL Server.

Here is my JSON :

[
  {
    "nodeId": 15,
    "nodeCondition": "needRepairing=true"
  },
  {
    "nodeId": 16,
    "nodeCondition": "needWashing=false"
  }
]

which is stored in a column. I want to delete elements by their nodeId.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I don’t think you can delete an item from JSON array, so you need to parse, filter and rebuild the JSON array again.

Table:

SELECT *
INTO JsonTable
FROM (VALUES
   (N'[
      {"nodeId":13,"nodeCondition":"needRepairing=true"},
      {"nodeId":14,"nodeCondition":"needRepairing=true"},
      {"nodeId":15,"nodeCondition":"needRepairing=true"},
      {"nodeId":16,"nodeCondition":"needWashing=false"}
      ]')
) v (JsonColumn)

Statement:

UPDATE JsonTable
SET JsonColumn = (
   SELECT nodeId, nodeCondition
   FROM OPENJSON(JsonColumn) WITH (
      nodeId int '$.nodeId', 
      nodeCondition nvarchar(1000) '$.nodeCondition'
   )
   WHERE nodeId NOT IN (13, 15)
   FOR JSON PATH
)

Result:

JsonColumn
[{"nodeId":14,"nodeCondition":"needRepairing=true"},{"nodeId":16,"nodeCondition":"needWashing=false"}]

Note, that in case of JSON object, you can delete a specific key with JSON_MODIFY(), using lax mode and NULL as new value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading