SQL FOR JSON发出简单数组

时间:2019-02-07 15:34:21

标签: sql json sql-server

使用MS SQL Server 2017,我有2个表:

  • 贷款:列包括贷款,OrganizationID
  • 组织:列包括OrganizationID

我的目标是生成JSON,其中包含一个包含组织的贷款编号的字符串数组。

我正在按照以下方式使用SQL:

SELECT
    OrganizationID,
    (   SELECT '[' + STRING_AGG('''' + Loan + '''', ',') + ']' 
        FROM Loan 
        WHERE Loan.OrganizationID = Organization.OrganizationID
    ) AS [Loans]
FROM Organization 
WHERE OrganizationID = 1
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;

我想得到

{
    "OrganizationID": 1,
    "Loans": ['Test 001','Test Loan 123','Test Loan 234']
}

但是,我实际得到的是用引号将“贷款”值包裹起来的:

{
    "OrganizationID": 1,
    "Loans": "['Test 001','Test Loan 123','Test Loan 234']"
}

我知道我可以做到:

SELECT
    OrganizationID,
    (   SELECT Loan 
        FROM Loan 
        WHERE Loan.OrganizationID = Organization.OrganizationID
        FOR JSON PATH
    ) AS [Loans]
FROM Organization 
WHERE OrganizationID = 1
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;

产生这个:

{
    "OrganizationID": 1,
    "Loans": [{
        "Loan": "Test 001"
    }, {
        "Loan": "Test Loan 123"
    }, {
        "Loan": "Test Loan 234"
    }]
}

但是,我的要求是生成一个简单的字符串数组,而不是一个Loan对象的数组。

关于如何塑造JSON的建议将不胜感激!

1 个答案:

答案 0 :(得分:3)

JSON字符串使用"作为分隔符,而不是'。另外,我们应注意转义(以防万一)。考虑到这些事项,JSON_QUERY将帮助我们:

SELECT
    OrganizationID,
    JSON_QUERY((   
        SELECT '[' + STRING_AGG('"' + STRING_ESCAPE(Loan, 'json') + '"', ',') + ']' 
        FROM Loan 
        WHERE Loan.OrganizationID = Organization.OrganizationID
    )) AS [Loans]
FROM Organization 
WHERE OrganizationID = 1
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER;