【问题标题】:JSON to SQL Server: Convert sub-array of values to columnJSON 到 SQL Server:将值的子数组转换为列
【发布时间】:2016-09-07 14:54:41
【问题描述】:

我有 JSON 之类的

{  
    "url": {
        "web_categories": [{ "id": 226 } , { "id": 401 }]
  },  
   "account":"Basic"  
}

我想在 SQL 中输出一列,其中包含与 URL 匹配的所有 web_categories 的 ID。

| webcat |
|--------|
| 226    |
| 401    |

使用 SQL Server 2016 / Azure SQL DB 对 JSON 的支持,如何实现?

可重现的例子

DECLARE @jsonInfo VARCHAR(MAX)  
SET @jsonInfo =N'{  
    "url": {
        "web_categories": [{ "id": 226 }]
  },  
   "account":"Basic"  
}'  

以前的迭代

select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories.id[0]')
select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories.id')
select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories')
select * from openjson(@jsonInfo,'$.url.web_categories.id[0]')
select * from openjson(@jsonInfo,'$.url.web_categories.id')
select * from openjson(@jsonInfo,'$.url.web_categories')
select JSON_QUERY(@jsonInfo, '$.url.web_categories.id[0]') webcat
select JSON_QUERY(@jsonInfo, '$.url.web_categories.id')    webcat
select JSON_QUERY(@jsonInfo, '$.url.web_categories')       webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories.id[0]') webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories.id')    webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories')       webcat

【问题讨论】:

  • 您是否要将您的答案标记为已接受?
  • 标记为已接受

标签: sql-server json azure-sql-database sql-server-2016


【解决方案1】:

使用默认架构,返回的记录带有 value 列,其中包含数组中每个项目的 JSON。然后需要处理这个 JSON。

DECLARE @jsonInfo VARCHAR(MAX)  
SET @jsonInfo =N'{  
    "url": {
        "web_categories": [{ "id": 226 },{ "id": 411 }]
  },  
   "account":101  
}'  


 SELECT JSON_VALUE(value,'$.id') AS ids FROM OPENJSON(@jsoninfo,'$.url.web_categories')

【讨论】:

  • 在这种情况下,显式模式可能不是更好的选择,因为它会直接将 id 转换为 int:select id from openjson(@jsonInfo,'$.url.web_categories') with (id int)跨度>
猜你喜欢
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 2022-08-12
相关资源
最近更新 更多