简体   繁体   English

在SQL中替换JSON格式的字符串

[英]Replacing JSON Formatted String in SQL

I have a something like this in my table column: 我的表格栏中有类似这样的内容:

{"InputDirection":0,"Mask":"AA","FormatString":null,"AutoCompleteValue":null,
 "Filtered":"0123456789","AutoComplete":false,"ReadOnly":true}

What I want to do is to change A to N in "Mask":"AA" and remove "Filtered":"0123456789" if they exist. 我想要做的是将"Mask":"AA" A更改为N,如果存在,则删除"Filtered":"0123456789" Mask could be in different forms like A9A , 'AAAA`, etc. 遮罩可以采用不同的形式,例如A9A ,“ AAAA”等。

If it was in C# I could do it by myself by parsing it to JSON, etc but I need to do it within SQL. 如果是在C#中,我可以自己将其解析为JSON等,但是我需要在SQL中进行。

I've found this article which shows how to parse JSON to Table . 我发现本文显示了如何将JSON解析为Table This gave me an idea that I can parse each field to temp table and make the changes on that and convert it back to JSON so update the actual field where I take this JSON field from. 这给了我一个主意,我可以将每个字段解析到temp表并对其进行更改,然后将其转换回JSON,以便更新从中获取此JSON字段的实际字段。 However, this looks like a cumbersome process for both me and the server. 但是,对于我和服务器而言,这似乎都是一个繁琐的过程。

Any better ideas? 还有更好的主意吗?

You can use this LINK . 您可以使用此LINK

And then use the following code 然后使用下面的代码

select * into #demo from
(Select * from parseJSON('{"InputDirection":0,"Mask":"AA","FormatString":null,"AutoCompleteValue":null,
 "Filtered":"0123456789","AutoComplete":false,"ReadOnly":true}

')) a

select * from #demo

--- CHANGE THE DATA HERE AS REQUIRED


DECLARE @MyHierarchy JSONHierarchy;
INSERT INTO @myHierarchy
select * from #demo;


-- USE THIS VALUE AND UPDATE YOUR JSON COLUMN
SELECT dbo.ToJSON(@MyHierarchy)


drop table #demo

I may be getting something wrong here but why can't you simply use REPLACE to update what's needed and LIKE to identify JSON strings that should be updated? 我在这里可能出错了,但是为什么您不能简单地使用REPLACE来更新需要的内容,而不能像LIKE那样标识应该更新的JSON字符串呢?

update table_T
set json_string = REPLACE(json_string, '"Filtered":"0123456789",', '')
where json_string like '%"Mask":"AA"%'

Not sure I understand why do you need to parse it…. 不知道我是否理解您为什么需要解析…。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM