Multiple SELECT statements into a single JSON

前端 未结 1 1427
[愿得一人]
[愿得一人] 2021-01-16 09:26

I\'m convinced this must be answered somewhere but for the life of me I just can\'t seem to find anything no matter how much I change my search phrases.

I need to se

相关标签:
1条回答
  • 2021-01-16 09:28

    According to the accepted answer of FOR JSON PATH. how to not use escape characters on SQL Server's forum on MSDN:

    FOR JSON will escape any text unless if it is generated as JSON result by some JSON function/query. In your example, FOR JSON cannot know do you really want raw JSON or you are just sending some free text that looks like JSON.

    Properly defined JSON is generated with FOR JSON (unless if it has WITHOUT_ARRAY_WRAPPER option) or JSON_QUERY. If you wrap your JSON literal with JSON_QUERY it will not be escaped.

    This answer got me to try the following code:

    DECLARE @Json nvarchar(max) = 
    (
        SELECT
         JSON_QUERY((
            SELECT 'Data1' AS [Data1], 'Data2' AS [Data2]
    
            FOR JSON PATH
            , INCLUDE_NULL_VALUES
            , WITHOUT_ARRAY_WRAPPER
        )) AS [Part1]
        ,
        JSON_QUERY((
            SELECT 'Text1' AS [Text1], 'Text2' AS [Text2]
    
            FOR JSON PATH
            , INCLUDE_NULL_VALUES
            , WITHOUT_ARRAY_WRAPPER
        )) AS [Part2]
    
        FOR JSON PATH
        , WITHOUT_ARRAY_WRAPPER
    );
    
    SELECT @Json;
    

    As as it turns out - this is working like a charm. Results:

    {
        "Part1": {
            "Data1": "Data1",
            "Data2": "Data2"
        },
        "Part2": {
            "Text1": "Text1",
            "Text2": "Text2"
        }
    }
    

    DB<>Fiddle


    Update Look what I found buried in official documentation:

    To avoid automatic escaping, provide newValue by using the JSON_QUERY function. JSON_MODIFY knows that the value returned by JSON_MODIFY is properly formatted JSON, so it doesn't escape the value.

    0 讨论(0)
提交回复
热议问题