4

Here is my code:

DECLARE @info NVARCHAR(MAX) = '{"searchQuery":{"reportType":"ReportedHcEcg"},"pageQuery":{"pageNumber":1,"pageSize":10,"sortColumnName":"Urgent, UploaDateTime","sortOrder":"Desc"}}'
SET @info = JSON_MODIFY(@info, '$.searchQuery.reportType', NULL)
SELECT @info

When I try to remove the reportType field in 2nd line of code my output should be the one by removing reportType from searchQuery like below

{"searchQuery":{},"pageQuery":{"pageNumber":1,"pageSize":10,"sortColumnName":"Urgent, UploaDateTime","sortOrder":"Desc"}}

Instead of that it is like below

{"searchQuery":{"pageSize":10,"sortColumnName":"Urgent, UploaDateTime","sortOrder":"Desc"}}

I can not understand this behavior of SQL Server. Is there any help for this?

4
  • 1
    This sure looks like a bug. Smallest repro: SELECT JSON_MODIFY('{"a":{"b":""},"c":{"d":"","e":""}}', '$.a.b', NULL) is {"a":{"e":""}}, while SELECT JSON_MODIFY('{"a":{"b":""},"c":{"d":""}}', '$.a.b', NULL) (note: only one property on the second object) gives the correct {"a":{},"c":{"d":""}}. If strict is used in the path, both cases correctly set a.b to null, so it seems like only deleting misfires. Commented Jul 26, 2018 at 12:43
  • 1
    Furthermore, this fails only when attempting to delete the only property of an object: SELECT JSON_MODIFY('{"a":{"b":"","c":""},"d":{"e":"","f":""}}', '$.a.b', NULL) yields the correct {"a":{"c":""},"d":{"e":"","f":""}}, and SELECT JSON_MODIFY('{"a":{"b":"","c":""},"d":{"e":"","f":""}}', '$.a.c', NULL) yields {"a":{"b":""},"d":{"e":"","f":""}}. This suggests some (fairly complicated) workarounds by adding dummy members and testing for emptiness. Commented Jul 26, 2018 at 12:52
  • Certainly looks like a bug. Nice find guys. I added a fiddle with @JeroenMostert example. sqlfiddle.com/#!18/dc377/6 Commented Jul 26, 2018 at 19:14
  • Repro here on SQL Server 2019 dbfiddle.uk/… Commented Jul 17, 2022 at 4:42

1 Answer 1

3

Here is a workaround: extract, edit, and replace the child object as an object.

DECLARE @info NVARCHAR(MAX) = '{"searchQuery":{"reportType":"ReportedHcEcg"},"pageQuery":{"pageNumber":1,"pageSize":10,"sortColumnName":"Urgent, UploaDateTime","sortOrder":"Desc"}}'
SET @info = JSON_MODIFY(@info, '$.searchQuery', JSON_MODIFY(JSON_QUERY(@info, '$.searchQuery'), '$.reportType', NULL))
SELECT @info
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.