简体   繁体   中英

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"
        }
    }
]

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"
        }
    ]
}

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-2025 STACKOOM.COM