json - 将 SQL Server 列的内容转换为 JSON 格式
问题描述
我有一个 SQL Server 表,其中有一列名为“过滤器”。
下面是用于创建示例表的 SQL Server 脚本:
CREATE TABLE dbo.TestJSON
(
TestJSONID INT IDENTITY(1,1),
[Filter] NVARCHAR(4000)
)
INSERT INTO dbo.TestJSON ([Filter])
VALUES ('$WYTS IN (''Control'', ''Machine'', ''Power'', ''DSP'', ''NM'', ''Digital'', ''AI'')')
现在我的目标是将列的内容转换Filter
为以下 JSON 格式:
"conditions":{
"condition":"AND",
"rules":[
{
"condition":"AND",
"operator":"IN",
"value":[
"Control",
"Machine",
"Power",
"DSP",
"NM",
"Digital",
"AI"
],
"type":"string"
}
]
}
我怎样才能做到这一点?
任何帮助将不胜感激。
提前致谢。:)
解决方案
这是一个选项
例子
Select [conditions.condition]='AND'
,[conditions.rules] = json_query(
(Select condition='AND'
,operator ='IN'
,value = json_query('['+replace(stuff(stuff(Filter,charindex(')',Filter),len(Filter),''),1,charindex('(',Filter),''),'''','"')+']')
,type = 'string'
For JSON Path )
)
From TestJSON
For JSON Path,Without_Array_Wrapper
结果
{
"conditions": {
"condition": "AND",
"rules": [
{
"condition": "AND",
"operator": "IN",
"value": [
"Control",
"Machine",
"Power",
"DSP",
"NM",
"Digital",
"AI"
],
"type": "string"
}
]
}
}
如果碰巧你需要转义字符串
Select [conditions.condition]='AND'
,[conditions.rules] = json_query(
(Select condition='AND'
,operator ='IN'
,value = json_query('['+replace(stuff(stuff(B.S,charindex(')',B.S),len(B.S),''),1,charindex('(',B.S),''),'''','"')+']')
,type = 'string'
For JSON Path )
)
From TestJSON A
Cross Apply ( values ( string_escape(Filter,'JSON') ) ) B(S)
For JSON Path,Without_Array_Wrapper
推荐阅读
- docker - Jenkins Dockerfile 可以工作,但不能在 docker-compose
- python - 如何在 Python 中使用正则表达式替换文件路径?
- spring-boot - 在 application.properties 中生成 LocalDateTime
- android - 轮换时重新加载警报对话框
- android - Android LocationManager 泄漏内存
- javascript - 解码错误:失败“期望带有名为 `gamegrid` 的字段的对象”
- python - 使用 pandas 从两列中获取值范围的优雅方法
- repast-simphony - Repast - 永久消除/删除代理
- excel - 在自动过滤器中使用数组
- c++ - 在 Visual Studio 2019 中添加 QMainWindow 类