Select last value from Json array

前端 未结 3 810
慢半拍i
慢半拍i 2021-01-22 16:00

I need to get the last item in an array from a JSON format. I have this JSON.

  @json =   
  N\'{ 
        \"solution\": \"xxxxxxxxxxxxxxxxxxxxx\",
        \"opt         


        
3条回答
  •  面向向阳花
    2021-01-22 16:42

    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.

提交回复
热议问题