首页 > 解决方案 > 如何在 SQL 中创建单个对象 JSON 数组?

问题描述

我正在尝试将一行数据转换为包含单个对象的 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必须是单个对象,Report并且Item必须是包含单个对象的数组。任何人都可以帮助格式化这样的数据吗?

标签: sqljsonsql-servertsql

解决方案


您需要如下声明:

;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

推荐阅读