【问题标题】:SQL to generate JSON with same column names and different aliasesSQL 生成具有相同列名和不同别名的 JSON
【发布时间】:2022-01-22 04:03:12
【问题描述】:

我正在尝试以这种格式从我的 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”而无法正常工作。

【问题讨论】:

    标签: sql json sql-server


    【解决方案1】:

    另一种可能的方法是为每一行生成嵌套的 JSON 对象 ('$."custom_fields"'),然后构建最终的 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() 的一些话 - 正如documentation 解释的那样 ... JSON_QUERY 返回一个有效的 JSON 片段。因此,FOR JSON 不会转义 JSON_QUERY 返回值中的特殊字符。如果您使用 FOR JSON 返回结果,并且包含已经采用 JSON 格式的数据(在列中或作为表达式的结果),请使用不带路径参数的 JSON_QUERY 包装 JSON 数据。

    注意,正如@Larnu 所说,这里不需要这一步。

    【讨论】:

    • 实际上是要编辑一些非常相似的东西作为替代方案。 :) 不过,据我所知,不需要JSON_QUERYdb<>fiddle
    • @Larnu,老实说,我的第一次尝试是您回答中的方法。 :)
    • @Larnu 不需要它的原因是直接的 FOR JSON 子查询被识别为 JSON,参见例如 dbfiddle.uk/… 无法识别的地方
    【解决方案2】:

    一种方法是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;
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      相关资源
      最近更新 更多