I need to get the last item in an array from a JSON format. I have this JSON.
@json =
N\'{
\"solution\": \"xxxxxxxxxxxxxxxxxxxxx\",
\"opt
First, your JSON string is malformed. You need to remove the comma after the closing array bracket.
So let's declare our variable:
DECLARE @json NVARCHAR(MAX) = N'{
"solution": "xxxxxxxxxxxxxxxxxxxxx",
"options": [
{
"choice_id": 205073,
"choice": "aaaa"
},
{
"choice_id": 205074,
"choice": "bbbb"
},
{
"choice_id": 205075,
"choice": "cccc"
},
{
"choice_id": 205076,
"choice": "ffffdd"
}
]
}'
Now you can use a combination of OPENJSON() and FOR JSON to get the last record in the array.
SELECT jsonfield = CAST((
SELECT TOP 1
j.solution
,o.choice_id
,o.choice
FROM
OPENJSON(@json)
WITH
(
solution VARCHAR(MAX) '$.solution'
,options NVARCHAR(MAX) '$.options' AS JSON
) j
CROSS APPLY
OPENJSON(options)
WITH
(
choice_id INT '$.choice_id'
,choice VARCHAR(4) '$.choice'
) o
ORDER BY o.choice_id DESC
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
) AS NVARCHAR(MAX))
EDIT:
Or you can use this query, if you don't want to order by any of the node values:
SELECT jsonfield = CAST((
SELECT TOP 1
j.solution
--,o.*
,c.choice_id
,c.choice
FROM OPENJSON(@json)
WITH
(
solution VARCHAR(MAX) '$.solution'
,options NVARCHAR(MAX) '$.options' AS JSON
) j
CROSS APPLY OPENJSON(options) o
CROSS APPLY OPENJSON(o.Value)
WITH (
choice_id int '$.choice_id',
choice varchar(4) '$.choice'
) c
ORDER BY [key] DESC
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
) AS NVARCHAR(MAX))