【问题标题】:Parsing a JSON based on a condition in SQL Server根据 SQL Server 中的条件解析 JSON
【发布时间】:2021-05-24 18:10:31
【问题描述】:

这是将要提供的 JSON 定义(只是一个简短的示例)以及我为获得预期结果而实现的代码:

declare @json nvarchar(max)

set @json = '{
   "testJson":{
      "testID":"Test1",
      "Value":[
         {
            "Value1":"",
            "Value2":"",
            "Value3":"",
            "Type": "1A"
         },
         {
            "Value1":"123",
            "Value2":"456",         
            "Value3":"Automatic",
            "Type": "2A"
         },
         {
            "Value1":"789",
            "Value2":"159",         
            "Value3":"Manual",
            "Value4":"Success"  ,
            "Type": "3A"
         }
      ]
   }
}'


select 
    'ValueFields' as groupDef,
    -- b.[key],
    -- c.[key],
    STRING_AGG( c.value , ' | ') as val
from 
    openjson(@json, '$.testJson.Value') as b
cross apply 
    openjson(b.value) as c
where 
    b.[key] not in (select b.[key]
                    from openjson(@json, '$.testJson.Value') as b
                    where b.value like ('%1A%'))

如您所见,数组中的每个元素都可以有不同数量的属性(value1,.., value4..),我只需要考虑那些 type 属性不等于“1A”的元素。该查询为我提供了请求的结果,但是,我想知道如何提高代码的性能,因为我在子选择中使用了 like 运算符,并且显然原始 JSON 文件可能在数组。

【问题讨论】:

    标签: arrays json sql-server parsing


    【解决方案1】:

    select b.Value --,c.value
    from 
    openjson(@json, '$.testJson.Value')
    with
    (
      Value nvarchar(max) '$' as json,
      Type varchar(100) '$.Type'
    ) as b
    --cross apply  openjson(b.Value) as c
    where b.Type <> '1A'
    

    【讨论】:

    • 非常感谢 Iptr。我认为这可以工作。
    • .. @d2907 ? ?
    【解决方案2】:
    SELECT 
        'ValueFields' as groupDef,
        J.value as val
    FROM
    OPENJSON(@json,'$.testJson.Value') J
    WHERE
        JSON_VALUE([value],'$.Type') <> '1A'
    

    【讨论】:

    • 谢谢你,罗斯,你的解决方案为我需要解析的另一个 json 提供了一个想法。
    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2019-08-02
    • 2014-04-27
    相关资源
    最近更新 更多