4

In Multi-Objects JSON array, I would like to modify all the values of objects and I have difficulty in accessing the values i.e.,

EXAMPLE--

DECLARE @json nvarchar(MAX)
SET @json = N'[{"name": "John","sex": "F"}, {"name": "Jane","sex": "F"}]'

I would like to modify sex value of all objects to "M".

JSON_MODIFY(@json, '$.Sex', 'M')

is not working. Are there any methods to solve my issue?

1 Answer 1

3

This should help

DECLARE @jsonstr NVARCHAR(MAX) = '[{"name": "John","sex": "F"}, {"name": "Jane","sex": "F"}]}'
;WITH CTE AS
(
  SELECT * FROM OPENJSON(@jsonstr)
  WITH ([name] VARCHAR(100) '$.name' , [sex] VARCHAR(100) '$.sex' )
)
,CTE1 AS
(
    SELECT [name], case when [sex] = 'F' THEN 'M' ELSE [sex] END [sex]
    FROM CTE
)
SELECT * 
FROM CTE1
FOR JSON AUTO
GO

OUTPUT

[{"name":"John","sex":"M"},{"name":"Jane","sex":"M"}]
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.