Is there a way/function/reg-ex in SQL Server or Visual Studio by which we can escape any character/special character within a string?
I have a functionality/page where there are server text field and user can enter any kind of string there (including special characters). And as a result I am showing a JSON string as a 'Key', 'Value' pare of those text fields entries.
For ex: I have these fields on a page:
Name , LastName , Address
And the entered values for above fields are:
Name : *-+-#. Wwweee4426554456666yyyy5uuuuttrrrreree6655zfgh\\][;'/.uuuuuuuu66uuyt,+_)(*&^%$#@!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$#@!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$#@!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$#@!~|}{:\
LastName : Piterson
Address : Park Road, LA
And I am showing the output like a JSON string below-
[{"Key":"Name","Value":"*-+-#.Wwweee4426554456666yyyy5uuuuttrrrreree6655zfgh\\][;'/.uuuuuuuu66uuyt,+_)(*&^%$#@!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$#@!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$#@!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$#@!~|}{:\"},{"Key":"LastName","Value":"Piterson"},{"Key":"Address","Value":"Park Road, LA"}]
But while parsing this string I am getting a parsing error below -
"After parsing a value an unexpected character was encountered: K. Path '[4].Value', line 1, position 1246."
I am using below SQL Server function to parse the string -
ALTER function [dbo].[fnEscapeString](@text nVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
as
BEGIN
--if(CHARINDEX() )
if (CHARINDEX('\',@text) > 0)
set @text = Replace(@text,'\','\\')
if (CHARINDEX('"',@text) > 0)
set @text = Replace(@text,'"','\"')
return @text
END
This function is working in many other cases (with many other strings). But not working with above string. I think this function is not enough able to parse all kind of strings.
So is there any way where we can parse a string in a valid JSON row format. May be any reg-ex or sql function can do that. Please suggest.