Select last value from Json array

前端 未结 3 809
慢半拍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:51

    You can try 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"
            }
        ]
    }';
    
    SELECT TOP 1 
             A.solution
            ,JSON_QUERY(B.[value]) AS options
    FROM OPENJSON(@json) WITH (solution nvarchar(max), options NVARCHAR(MAX) AS JSON) A
    CROSS APPLY OPENJSON(A.options) B
    ORDER BY B.[key] DESC
    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;
    

    The result

    {"solution":"xxxxxxxxxxxxxxxxxxxxx"
    ,"options":{
                "choice_id": 205076,
                "choice": "ffffdd"
               }
    }
    

    Some explanation

    FROM OPENJSON will dive into your JSON and find the top-level elements. We fetch solution as is and we state AS JSON for options to specify, that this value will be treated as JSON later on.

    The CROSS APPLY will call OPENJSON again, but this time against the options and we will get an array back. The column key is the ordinal position within the array, so we can use TOP 1 and ORDER BY key DESC to get the last element in the array.

    Before we can re-assemble this query to a JSON we have to wrap B.value with JSON_QUERY(). Otherwise we would see escaped characters like \t or \r\n within the JSON. The reason: Without this, the JSON-string would not be taken as a JSON-string but as any other string and would be packed into the result as one single text value.

提交回复
热议问题