I need to get the last item in an array from a JSON format. I have this JSON.
@json =
N\'{
\"solution\": \"xxxxxxxxxxxxxxxxxxxxx\",
\"opt
You can either shred with OPENJSON and re-assemble the document FOR JSON (see @digital.aaron's answer), or use JSON_MODIFY, like this:
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"
}
]
}'
declare @options nvarchar(max) = (
select top 1 value
from openjson(@json,'$.options')
order by [key] desc
);
set @json = json_modify(@json, '$.options', json_query(@options))
select @json
Outputs
{
"solution": "xxxxxxxxxxxxxxxxxxxxx",
"options": {
"choice_id": 205076,
"choice": "ffffdd"
}
}
Note that the JSON_QUERY function is also used for parsing a string into a JSON fragment. Without that, the value in @options would be inserted as a single string value, instead of a json object.