Search code examples
jsonsql-serversql-server-2016

sql output json structure


I need to get the following output about the sql query:

{
    "records": [
        {
            "attributes": {
                "type": "customer"
            },
            "name": "test 1",
            "email": "test1@test.com"
        },
        {
            "attributes": {
                "type": "customer"
            },
            "name": "test 2",
            "email": "test2@test2.com"
        }
    ]
}

my attempt:

DECLARE @ttCustomer table (cname nvarchar(50),
                           email nvarchar(250));
INSERT @ttCustomer
VALUES ('test 1', 'test1@test.com');
INSERT @ttCustomer
VALUES ('test 2', 'test2@test.com');
SELECT 'customer' AS [records.attributes.type],
       cname AS [records.name],
       email AS [records.email]
FROM @ttCustomer
FOR JSON PATH;

almost perfect output result

[
    {
        "records": {
            "attributes": {
                "type": "customer"
            },
            "name": "test 1",
            "email": "test1@test.com"
        }
    },
    {
        "records": {
            "attributes": {
                "type": "customer"
            },
            "name": "test 2",
            "email": "test2@test.com"
        }
    }
]

Solution

  • Just define your ROOT:

    DECLARE @ttCustomer table (cname nvarchar(50),
                               email nvarchar(250));
    INSERT @ttCustomer
    VALUES ('test 1', 'test1@test.com');
    INSERT @ttCustomer
    VALUES ('test 2', 'test2@test.com');
    SELECT 'customer' AS [attributes.type],
           cname AS [name],
           email AS [email]
    FROM @ttCustomer
    FOR JSON PATH, ROOT('records');
    

    Outputs:

    {
        "records": [
            {
                "attributes": {
                    "type": "customer"
                },
                "name": "test 1",
                "email": "test1@test.com"
            },
            {
                "attributes": {
                    "type": "customer"
                },
                "name": "test 2",
                "email": "test2@test.com"
            }
        ]
    }