4

I want to delete the "AttributeName" : "Manufacturer" from the below json in SQL Server 2016:

declare @json nvarchar(max) = '[{"Type":"G","GroupBy":[],
"Attributes":[{"AttributeName":"Class Designation / Compressive Strength"},{"AttributeName":"Size"},{"AttributeName":"Manufacturer"}]}]'

This is the query I tried which is not working

select JSON_MODIFY((
select JSON_Query(@json, '$[0].Attributes') as res),'$.AttributeName.Manufacturer', null) 
4

1 回答 1

3

这是使用for jsonopen json的工作解决方案。重点是:

  1. 确定您要删除的项目并将其替换为NULL。这是由JSON_MODIFY(@json,'$[0].Attributes[2]', null). 我们只是说,取第二个元素Attributes并将其替换为 null

  2. 将此数组转换为行集。我们需要以某种方式摆脱这个null元素,这是我们可以在 SQL 中轻松过滤的东西where [value] is not null

  3. 将其全部组装回原始 JSON。这是由FOR JSON AUTO

请记住此类 JSON 数据转换的一个重要方面:

JSON 是为信息交换或最终存储信息而设计的。但是您应该避免在 SQL 级别上进行更复杂的数据操作。

无论如何,这里的解决方案:

declare @json nvarchar(max) = '[{"Type": "G","GroupBy": [],"Attributes": [{"AttributeName": "Class Designation / Compressive Strength"}, {"AttributeName": "Size"}, {"AttributeName": "Manufacturer"}]}]';            

with src as
(
    SELECT * FROM OPENJSON(
        JSON_Query(
            JSON_MODIFY(@json,'$[0].Attributes[2]', null) , '$[0].Attributes'))
)
select JSON_MODIFY(@json,'$[0].Attributes', (
    select JSON_VALUE([value], '$.AttributeName') as [AttributeName] from src
    where [value] is not null
    FOR JSON AUTO 
)) 
于 2017-11-03T12:23:08.777 回答