【问题标题】:How to create a single object JSON array in SQL?如何在 SQL 中创建单个对象 JSON 数组?
【发布时间】:2020-04-06 05:59:48
【问题描述】:

我正在尝试将一行数据转换为包含单个对象的 JSON 数组。一列包含 XML,它概述了另一个转换为数组的单个对象。

我的查询:

WITH r AS (
SELECT TOP 1 * FROM Table1
ORDER BY RecordID ASC)

SELECT 
NEWID() AS 'Report.ReportUUID', 
Value1 as 'Report.Value1', 
Value2 as 'Report.Value2',
DateTime as 'Report.DateTime',
UserID as 'Report.UserID',
'Medium' as 'Report.Priority',
NEWID() as 'Report.Item.ItemUUID',
XML.value('category[1]', 'varchar(100)') as 'Report.Item.Category',
XML.value('description[1]', 'varchar(1000)') as 'Report.Item.Description',
XML.value('date[1]', 'varchar(100)') AS 'Report.Item.DateTime'
FROM r
FOR JSON PATH, ROOT('DataSet');

期望的输出:

{
  "DataSet" : {
    "Report" : [
      {
        "ReportUUID" : "uuid here",
        "Value1" : "value1",
        "Value2" : "value2",
        "DateTime" : "2020-04-06 16:00:00",
        "UserID" : "1234",
        "Priority" : "Medium",
        "Item" : [
          {
            "ItemUUID" : "uuid here",
            "Category" : "01",
            "Description" : "Desc",
            "DateTime" : "2020-04-05 08:00:00"
          }
        ]
      }
    ]
  }
}

实际输出:

{
    "DataSet": [
        {
            "Report": {
                "ReportUUID" : "uuid here",
                "Value1": "value1",
                "Value2": "value2",
                "DateTime": "2020-04-06 16:00:00",
                "UserID": "1234",
                "Priority": "Medium",
                "Item": {
                    "ItemUUID": "uuid here",
                    "Category": "01",
                    "Description": "Desc",
                    "DateTime": "2020-04-05 08:00:00"
                }
            }
        }
    ]
}

DataSet 必须是单个对象,ReportItem 必须是包含单个对象的数组。任何人都可以帮助格式化这样的数据吗?

【问题讨论】:

  • 使用的 SQL Server 版本是什么?
  • Microsoft SQL Server 2017,版本 13.0.5101.9

标签: sql json sql-server tsql


【解决方案1】:

您需要如下语句:

;WITH r AS (
   SELECT TOP 1 * FROM Table1
   ORDER BY RecordID ASC
)
SELECT Report AS 'DataSet.Report'
FROM (
   SELECT 
      NEWID() AS 'ReportUUID', 
      Value1 as 'Value1', 
      Value2 as 'Value2',
      DateTime as 'DateTime',
      UserID as 'UserID',
      'Medium' as 'Priority',
      (
      SELECT 
         NEWID() as 'ItemUUID',
         XML.value('category[1]', 'varchar(100)') as 'Category',
         XML.value('description[1]', 'varchar(1000)') as 'Description',
         XML.value('date[1]', 'varchar(100)') AS 'DateTime'
      FOR JSON PATH   
      ) AS 'Item'
   FROM r
   FOR JSON AUTO
) t (Report)
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER

【讨论】:

    猜你喜欢
    • 2018-08-15
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多