sql输出json结构

qlckcl4x  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(119)

我需要获得有关SQL查询的以下输出:

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

我的尝试:

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;

近乎完美的输出结果

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

gab6jxml1#

只需定义您的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');

输出:

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

相关问题