Hakuna N
Hakuna N

Reputation: 181

Convert a mssql openjson array type value result to a table?

I have a json object in my Microsoft (MS) SQL Server query. This JSON object does have one value, which is an array of strings.

--this variable holds my JSON object with a value of array type. 
declare @json nvarchar(max) = N'{
                    "value": [
                        "tapiwanashe",
                        "robert",
                        "emmerson",
                        "ruwimbo",
                        "takudzwa",
                        "munyaradzi"
                    ]
                }'

My goal is to write a SQL query using the supported MS SQL Server JSON functions that produces a table with one column and six rows of the values in the JSON object value array above.

I have tried to run the JSON_QUERY and the OPENJSON functions. However, both of the two functions return an array of strings as the output. I would like to have a result with one column and six rows.

select JSON_QUERY(@json, '$.value')
select [value] from OPENJSON(@json)

The result I am getting is:

value
---------------
[
   "tapiwanashe",
   "robert",
   "emmerson",
   "ruwimbo",
   "takudzwa",
   "munyaradzi"
]

However, the result I am expecting to get looks like this:

value
-----------
tapiwanashe
robert
emmerson
ruwimbo
takudzwa
munyaradzi

The result must preserve the order on which the values appear in the value array.

Upvotes: 3

Views: 1835

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89424

Like this:

declare @json nvarchar(max) = N'{
                    "value": [
                        "tapiwanashe",
                        "robert",
                        "emmerson",
                        "ruwimbo",
                        "takudzwa",
                        "munyaradzi"
                    ]
                }'

select value 
from openjson(@json,'$.value')
order by [key]

outputs

value
----------
tapiwanashe
robert
emmerson
ruwimbo
takudzwa
munyaradzi

Upvotes: 5

Related Questions