如何以JSON

时间:2018-08-16 23:29:55

标签: json sql-server tsql

假设我有一个表FamousPeople和一个列Name,并带有3个名称:

  1. John
  2. Mary
  3. Freddie Mercury

这样做:

SELECT
    'Some Random Value' AS someColumnName,
    (SELECT name FROM FamousPeople
     FOR JSON PATH) AS famousPeopleName
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER

我得到这个结果:

{
  "someColumnName": "Some Random Value",
  "famousPeopleName":
  [
    {"name":"John"},
    {"name":"Mary"},
    {"name":"Freddie Mercury"}
  ]
}

我想知道是否有任何方法可以将famousPeopleName结果列作为字符串数组获取:

{
  "someColumnName": "Some Random Value",
  "famousPeopleName":
  [
    "John",
    "Mary",
    "Freddie Mercury"
  ]
}

当然,仅使用T-SQL功能,就不会在T-SQL中使用疯狂的科学家字符串操作(在荷兰也称为kick)

1 个答案:

答案 0 :(得分:0)

您可以使用JSON_QUERYFOR XML构建数组,然后提取整个json片段:

declare @FamousPeople table([name] varchar(50))

insert into @FamousPeople values
('John'),('Mary'),('Freddie Mercury')

SELECT 'Some Random Value' AS someColumnName,
JSON_QUERY(
    '[' + STUFF(( SELECT ',' + '"' + [name] + '"' 
    FROM @FamousPeople 
    FOR XML PATH('')),1,1,'') + ']' ) famousPeopleName  
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER 

结果:

{
    "someColumnName": "Some Random Value",
    "famousPeopleName": 
    [
        "John",
        "Mary",
        "Freddie Mercury"
    ]
}