我正在嘗試以這種格式從 SSMS 中的 SQL 資料生成 JSON:
{
"id": "1234",
"first_name": "Hasan",
"last_name": "Mahmud",
"custom_fields": [
{
"custom_field_name": "CPRCertified",
"custom_field_value": "Y"
},
{
"custom_field_name": "IsAttorney",
"custom_field_value": "N"
}
]
}
我正在嘗試這個:
SELECT e.Empl_ID AS id,
e.FirstName AS first_name,
e.LastName AS last_name,
'CPRCertified' AS [custom_fields.custom_field_name],
e.CPRCertified AS [custom_fields.custom_field_value],
'IsAttorney' AS [custom_fields.custom_field_name],
e.IsAttorney AS [custom_fields.custom_field_value]
FROM #e e
WHERE e.Empl_ID = '1234'
FOR JSON PATH;
但我收到此錯誤:
由于與其他列名或別名沖突,無法在 JSON輸出中生成屬性“custom_fields.custom_field_name” 。
對 SELECT 串列中的每一列使用不同的名稱和別名。
我已經嘗試過這個主題SQL to JSON - Grouping Results into JSON Array 但不起作用,因為我多次使用相同的“custom_field_name”。
uj5u.com熱心網友回復:
另一種可能的方法是'$."custom_fields"'為每一行生成嵌套的 JSON 物件 ( ),然后構建最終的 JSON:
SELECT
e.Empl_ID AS id,
e.FirstName AS first_name,
e.LastName AS last_name,
(
SELECT *
FROM (VALUES
('CPRCertified', e.CPRCertified),
('IsAttorney', e.IsAttorney)
) v (custom_field_name, custom_field_value)
FOR JSON PATH
) AS custom_fields
FROM (VALUES
('1234', 'Hasan', 'Mahmud', 'Y', 'N')
) e (Empl_ID, FirstName, LastName, CPRCertified, IsAttorney)
WHERE e.Empl_ID = '1234'
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER
關于轉義和的一些詞JSON_QUERY()- 正如檔案所解釋的...... JSON_QUERY 回傳一個有效的 JSON 片段。因此,FOR JSON 不會轉義 JSON_QUERY 回傳值中的特殊字符。如果您使用 FOR JSON 回傳結果,并且您包含已經采用 JSON 格式的資料(在列中或作為運算式的結果),請使用不帶路徑引數的 JSON_QUERY 包裝 JSON 資料。.
請注意,正如@Larnu 所評論的,此處不需要此步驟。
uj5u.com熱心網友回復:
一種方法是UNPIVOT您的資料(使用VALUES表結構),然后切換到JSON AUTO:
SELECT e.Empl_ID AS id,
e.FirstName AS first_name,
e.LastName AS last_name,
custom_fields.custom_field_name,
custom_fields.custom_field_value
FROM #e e
CROSS APPLY (VALUES(N'CPRCertified',e.CPRCertified),
(N'IsAttorney',e.IsAttorney))custom_fields(custom_field_name,custom_field_value)
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/387455.html
標籤:sql json sql-server
