The data that I'm trying to parse sometimes contains a single string value, other times, it contains an array of values.
For example, this works fine:
SELECT
color
FROM
OPENJSON('{"name": "Christmas Tree","color": "Green"}')
WITH (color NVARCHAR(MAX) '$.color' )
But if I have an array in there instead, it fails:
SELECT
color
FROM
OPENJSON('{"name": "Candy Cane","color": ["Red","White"]}')
WITH (color NVARCHAR(MAX) '$.color')
I can fix that by adding "AS JSON" inside the OPENJSON call:
SELECT
color
FROM
OPENJSON('{"name": "Candy Cane","color": ["Red","White"]}')
WITH (color NVARCHAR(MAX) '$.color' AS JSON)
But now the original call breaks:
SELECT
color
FROM
OPENJSON('{"name": "Christmas Tree","color": "Green"}')
WITH (color NVARCHAR(MAX) '$.color' AS JSON)
Is there a way to handle both cases in one shot? Or do I have to try one, check for a null result, then try the other?
Changing the data to be consistent isn't an option, I'm dealing with someone else's data.
I'm eventually turning the single string value into an array that contains a single value, so it's ok to return the data that way (ie, it's ok to get ['Green'] instead of 'Green')
DB-Fiddle here: https://www.db-fiddle.com/f/929e5vraAp9vsJGFPXRf5F/1
UNION ALLthe two queries then filter the one that doesn't have NULL. But this is probably not useful for real life examples