How do I keep FOR JSON PATH from escaping query results?

前端 未结 3 1308
小鲜肉
小鲜肉 2021-01-12 08:28

I\'m trying to write a fairly complicated SQL Query that produces JSON as the result. All is working great except for some hardcoded arrays I need to have deeper in the hier

3条回答
  •  猫巷女王i
    2021-01-12 09:07

    I have found one possible solution but I really don't like it. I'm posting what I have in hopes that somebody has a better solution.

    Using a WHERE statement on every branch of my UNION with either the affirmative or exact negative of my CASE statement can prevent the "strigifying" of my results.

    For example, this query:

    SELECT
        'Hi' AS Greeting,
        (
            SELECT * FROM
            (
                SELECT 'asdf' AS Stuff WHERE DatePart(second, GetDate()) % 2 = 0
                UNION ALL
                SELECT 'qwerty' AS Stuff WHERE DatePart(second, GetDate()) % 2 = 1
                UNION ALL
                SELECT 'zxcvb' AS Stuff WHERE DatePart(second, GetDate()) % 2 = 1
            ) AS SubSelect
            FOR JSON PATH
        ) AS Try1
    FOR JSON PATH
    

    provides these results:

    [
        {
            "Greeting": "Hi",
            "Try1": [
                {
                    "Stuff": "qwerty"
                },
                {
                    "Stuff": "zxcvb"
                }
            ]
        }
    ]
    

    If nothing better can be found, I can move forward with this. But this seems like a hacky way to control this.

提交回复
热议问题