首页 > 解决方案 > 将 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"
        }
    ]
}

我怎样才能做到这一点?

任何帮助将不胜感激。

提前致谢。:)

标签: jsonsql-server

解决方案


这是一个选项

例子

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 

推荐阅读