Here's the issue. I have a column in my database (type nvarchar(max)) that I am storing JSON in. I am storing both plain strings or objects in that column like the following:
JsonTable
|--|-------------------|
|Id|JsonValue |
|--|-------------------|
|0 |{"sample":"object"}|
|--|-------------------|
|1 |"plain-string" |
|--|-------------------|
I am trying to use JSON_MODIFY to merge these values with another table's values.
The following works fine for just objects, but not strings:
SELECT JSON_MODIFY('{}', '$.Values', JSON_QUERY(JsonValue))
FROM JsonTable
WHERE Id = 0 -- Fails when string is included in results
-- Result = |------------------------------|
|{"Values":{"sample":"object"} |
|------------------------------|
However it fails to parse the ordinary string (understandably since it is not JSON) So then my solution was to add a case statement to handle strings. However this does not work as wrapping it in a CASE statement string escapes the JSON_QUERY object and garbles it up in the final JSON_MODIFY result.
The following does not work as expected:
SELECT JSON_MODIFY('{}', '$.Values',
CASE
WHEN ISJSON(JsonValue) > 0 THEN JSON_QUERY(JsonValue)
ELSE REPLACE(JsonValue, '"','')
END)
FROM JsonTable
-- Result = |-------------------------------------|
|{"Values":"{\"sample\"::\"object\"}" |
|-------------------------------------|
|{"Values":"plain-string" |
|-------------------------------------|