从 openjson SQL Server 2016 中的嵌套数组中删除一个对象
Delete an object from nested array in openjson SQL Server 2016
我想在 SQL Server 2016 中从下面的 json 中删除 "AttributeName" : "Manufacturer"
:
declare @json nvarchar(max) = '[{"Type":"G","GroupBy":[],
"Attributes":[{"AttributeName":"Class Designation / Compressive Strength"},{"AttributeName":"Size"},{"AttributeName":"Manufacturer"}]}]'
这是我试过的查询,但无效
select JSON_MODIFY((
select JSON_Query(@json, '$[0].Attributes') as res),'$.AttributeName.Manufacturer', null)
这是使用 for json and open json 的工作解决方案。重点是:
确定您要删除的项目并将其替换为 NULL
。这是由 JSON_MODIFY(@json,'$[0].Attributes[2]', null)
完成的。我们只是说,取 Attributes
中的第二个元素并将其替换为 null
将此数组转换为行集。我们需要以某种方式摆脱这个 null
元素,这是我们可以通过 where [value] is not null
在 SQL 中轻松过滤的东西
Assemble 一切恢复原状 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
))
我想在 SQL Server 2016 中从下面的 json 中删除 "AttributeName" : "Manufacturer"
:
declare @json nvarchar(max) = '[{"Type":"G","GroupBy":[],
"Attributes":[{"AttributeName":"Class Designation / Compressive Strength"},{"AttributeName":"Size"},{"AttributeName":"Manufacturer"}]}]'
这是我试过的查询,但无效
select JSON_MODIFY((
select JSON_Query(@json, '$[0].Attributes') as res),'$.AttributeName.Manufacturer', null)
这是使用 for json and open json 的工作解决方案。重点是:
确定您要删除的项目并将其替换为
NULL
。这是由JSON_MODIFY(@json,'$[0].Attributes[2]', null)
完成的。我们只是说,取Attributes
中的第二个元素并将其替换为 null将此数组转换为行集。我们需要以某种方式摆脱这个
null
元素,这是我们可以通过where [value] is not null
在 SQL 中轻松过滤的东西
Assemble 一切恢复原状 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
))