Replacing JSON Formatted String in SQL - 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 could be in different forms like A9A, 'AAAA`, etc.
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.
I've found this article which shows how to parse JSON to 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. However, this looks like a cumbersome process for both me and the server.
Any better ideas?

You can use this 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?
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….

Related

How to use json array in WHERE IN clause in Postgres

I have a Postgres query like this
SELECT * FROM my_table WHERE status IN (2,1);
This is part of a big query, but I am facing an issue with the WHERE IN part here. I am using this query inside a function and the input parameters are in JSON format. Now the status values I am getting in in the form of a JSON array and it will be like status=[2,1]. I need to use this array in the WHERE clause in the query and not sure how to do that. Currently, I am using like
SELECT * FROM my_table WHERE status IN (array([2,1]));
But this is giving me an error. The status column is of smallint data type. I know this is simple, but I am very much new to Postgres and could not figure out any method to use the JSON array in WHERE IN clause. Any help will be appreciated.

use Json auto into open Json in SQL

Is this syntax possible in SQL:
SELECT *
FROM OPENJSON(SELECT * FROM FoodSara_tbl FOR JSON AUTO)
If yes, can you explain me how and why?
If no, Why? and what is the beast way instead of that?
this query work correct !!!
SELECT *
FROM OPENJSON(CONVERT(NVARCHAR(MAX),(SELECT * FROM [dbo].[temp1] FOR JSON AUTO)))
OPENJSON command give a string contain a json data as parameter
but when you generate json from table you have a pure json as result Set
and OPENJSON give a string parameter as json.
The two are different
if you run this code
SELECT * FROM [dbo].[temp1] FOR JSON AUTO
you see this result
[{"Pname":"Ava","Pregion":"German","Pcount":10},{"Pname":"Ava","Pregion":"UK","Pcount":5}]
if put this result on OPENJSON
SELECT *
FROM OPENJSON([{"Pname":"Ava","Pregion":"German","Pcount":10},{"Pname":"Ava","Pregion":"UK","Pcount":5}])
see below error
Invalid column name '{"Pname":"Ava","Pregion":"German","Pcount":10},{"Pname":"Ava","Pregion":"UK","Pcount":5}'.
but if you add ' at the first and foremost of your json. its parse correct
' is sign of string in SQL Server

I inserted the json file into my table, but how do i put in the date into my table as well?

Here is how my table is turning out. All I have left to do is insert the current
date in the dateloaded:
I've been trying to add a date when the data from the JSON file is loaded into the table but don't know the correct syntax. Any help please? :)
Taken from your comment below another answer:
That didn't quite work this was the error "Column name or number of
supplied values does not match table definition."
The issue you have is related to
insert into main.jsontable
select * from...
You should never rely on the columns order. The columns you are inserting to and the columns you are reading from must match. The worst case is a wrong match by coincidence.
About bad habits to kick: SELECT with *
Change this to
insert into main.jsontable(name, surname, email, ...more columns...)
select <list your JSON "columns" here>
from...
The final step then is to include the dateloaded to this:
insert into main.jsontable(dateloaded, name, surname, email, ...more columns...)
select SYSUTCDATETIME(), <list your JSON "columns" here>
from...
UPDATE
You were told already, that posting pictures is something to avoid. It's hard to read from there, but it seems you are trying to solve this here
with(
[dateloaded] datetimeoffset,
[name] ...
This derived column will never get any value as you are not reading this out of your JSON.
You can use GETDATE(), is actual datetime.
sysdatetimeofffset() should do what you want. Line up the columns, and something like the following should work:
select *, sysdatetimeoffset() from
openjson(#PersonDetails, <etc>

Postgres JSON selecting a row by list

I have a table that has a JSON list as one of its values. The column name is list_order and the value would be something like: [1,2,3].
I am having trouble doing a WHERE comparison to select by list_order. In pure SQL, it would be: SELECT * FROM table_name list_order=[1,2,3];
The closest example I found was this: How do I query using fields inside the new PostgreSQL JSON datatype?. However, this grabs the value of a key in the JSON where the JSON is a dictionary and not a list. I've tried modifying it to suit my need but it did not work.
Any suggestions? Is that even possible? Why is not documented? Thanks!
I found the answer. I need to compare it as text:
"SELECT * FROM table WHERE list_order::text='[1,2,3]';

Use a LIKE statement on SQL Server XML Datatype

If you have a varchar field you can easily do SELECT * FROM TABLE WHERE ColumnA LIKE '%Test%' to see if that column contains a certain string.
How do you do that for XML Type?
I have the following which returns only rows that have a 'Text' node but I need to search within that node
select * from WebPageContent where data.exist('/PageContent/Text') = 1
Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.
SELECT *
FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'
I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.
This might not be the best performing solution, so think twice before deplying it to production. It is however very usefull for a quick debug session, which is where I mostly use it.
EDIT: As Cliff mentions it, you could use:
...nvarchar if there's characters that don't convert to varchar
You should be able to do this quite easily:
SELECT *
FROM WebPageContent
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'
The .value method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.
Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:
create a stored function which gets the XML and returns the value you're looking for as a VARCHAR()
define a new computed field on your table which calls this function, and make it a PERSISTED column
With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).
Marc
Another option is to search the XML as a string by converting it to a string and then using LIKE. However as a computed column can't be part of a WHERE clause you need to wrap it in another SELECT like this:
SELECT * FROM
(SELECT *, CONVERT(varchar(MAX), [COLUMNA]) as [XMLDataString] FROM TABLE) x
WHERE [XMLDataString] like '%Test%'
This is what I am going to use based on marc_s answer:
SELECT
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)
FROM WEBPAGECONTENT
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0
Return a substring on the search where the search criteria exists