0

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.

7
  • Why are you storing JSON in SQL Server in the first place? Why isn't your database normalized? Commented Mar 29, 2022 at 11:03
  • Exactly what version of SQL Server are you using? Different versions of SQL Server have different JSON-processing capabilities.... Commented Mar 29, 2022 at 11:04
  • Do you have any requirements w.r.t. transactional safety? Commented Mar 29, 2022 at 11:04
  • Does the stored JSON always have only nodeId and nodeCondition kay\value pairs? Commented Mar 29, 2022 at 11:06
  • 1
    @MustafaBazghandi, I don't think you can delete an item from JSON array, so you need to parse, filter and rebuild the JSON array again. Commented Mar 29, 2022 at 11:12

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

for example , if you want to remove nodeId 16 then you could try this :

DECLARE @YourJson NVARCHAR(MAX) = N'[
{"nodeId":15,"nodeCondition":"needRepairing=true"},
{"nodeId":16,"nodeCondition":"needWashing=false"}
]';
SELECT * FROM (SELECT * FROM OPENJSON(@YourJson) WITH(nodeId 
INT,nodeCondition NVARCHAR(MAX)) WHERE nodeId <> 16) AS R FOR JSON 
AUTO;
GO 

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.