简体   繁体   中英

T-SQL - JSON Nested Objects - 1 row vs. multiple rows

Here is the table definition:

key_en, text_en, html_text_en, key_fr, text_fr, html_text_fr

Here is my query:

SELECT  
    [key_en] AS 'en.key'
    ,[text_en] AS 'en.text'
    ,[html_text_en] AS 'en.htmltext'
    ,[key_fr] AS 'fr.key'
    ,[text_fr] AS 'fr.text'
    ,[html_text_fr] AS 'fr.htmltext'
FROM [MyContent]
FOR JSON PATH;

The result I get as JSON is correct.

[
    {
        "en": {
            "key": "key en",
            "text": "text en",
            "htmltext": "html en"
        },
        "fr": {
            "key": "key fr",
            "text": "text fr",
            "htmltext": "html fr"
        }
    },
    {
        "en": {
            "key": "key2 en",
            "text": "text2 en",
            "htmltext": "html2 en"
        },
        "fr": {
            "key": "key2 fr",
            "text": "text2 fr",
            "htmltext": "html2 fr"
        }
    }
]

However the result set is in a single row (very long string).

I'd like to spread the result set across as many rows as the data in the table. The expected result should be:

    ROW 1 
    {
        "en": {
            "key": "key en",
            "text": "text en",
            "htmltext": "html en"
        },
        "fr": {
            "key": "key fr",
            "text": "text fr",
            "htmltext": "html fr"
        }
    }

    ROW 2 
    {
        "en": {
            "key": "key2 en",
            "text": "text2 en",
            "htmltext": "html2 en"
        },
        "fr": {
            "key": "key2 fr",
            "text": "text2 fr",
            "htmltext": "html2 fr"
        }
    }

What changes do I have to bring to reach my goal?

You can use this modified query which will return a row of JSON per row of your table:

SELECT  (
        SELECT  [key_en] AS 'en.key',
                [text_en] AS 'en.text',
                [html_text_en] AS 'en.htmltext',
                [key_fr] AS 'fr.key',
                [text_fr] AS 'fr.text',
                [html_text_fr] AS 'fr.htmltext'
          FOR JSON PATH
        )
  FROM  [MyContent]

You can use apply :

SELECT j.j
FROM [MyContent] c CROSS APPLY
     (SELECT c.[key_en] AS 'en.key',
             c.[text_en] AS 'en.text',
             c.[html_text_en] AS 'en.htmltext',
             c.[key_fr] AS 'fr.key',
             c.[text_fr] AS 'fr.text',
             c.[html_text_fr] AS 'fr.htmltext'
      FOR JSON PATH
     ) j(j);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM