escape or replace double quotes from form-field - json

I have a form-field (textarea) in my application, which may contain double-quotes (""). For a JSON-String, I wrote a small "setup", which is send afterwards. I encountered the problem, that if a user uses the double-quotes, my setup breaks.
This is how it looks like so far:
dim payload
payload = payload & "{""short_description"":""" & Replace(Replace(trim(shortDesc),chr(10),""), chr(13), "") & ""","
payload = payload & """description"":""" & Replace(Replace(trim(Description),chr(10),""), chr(13), "") &""","
payload = payload & """u_requester"":"""& sgi &""","
payload = payload & """contact_type"":""Self-service"","
payload = payload & """cmdb_ci"":""" & system &""","
payload = payload & """u_category"":""" & category & """}"
And just to show you where I'm using it:
With http
Call .Open("POST", url, False)
Call .SetRequestHeader("Accept", "application/json")
Call .SetRequestHeader("Content-Type", "application/json")
Call .Send(payload)
End With
The variables used in this method are arguments in the current function.
I thought about escaping double-quotes, but I somehow just end up on sites which suggest I should use chr(34) in a Response.Write, which isn't what I'm looking for.
I also tried to use the Replace-function, similar how I would do this in PHP:
Replace(myvar, '"'; "'")
But as you may figured out, a single-quote starts a comment in classic ASP. How can I get rid off the double-quotes here? It doesn't really matter if I convert " to ' or keep the double-quotes. Any suggestion is appreciated

If you need a visible double quote within a string in asp, you need to double it.
Response.Write("""")
If you want to replace a double quote,
str = Replace(str,"""","")

to display a double quote (or single quote) in a json string, you need to escape it:
str = "this is a ""test""."
strForJson = Replace( str, """", "\""" )

Related

Build large string in VBA with quotes

I need to build a large string (json) in VBA with quotes in it.
I tried this approach:
Dim payload As String
payload = ""
payload = payload & CHR(34) & {"timeframeId":13,"startDate":"2021-05-31 00:00:00.000","endDate":"2021-05-31 00:00:00.000","peopleList":[{"id":123}], & CHR(34)
...more lines building string
But the Excel IDE for VBA complains of a syntax error - presumeably to do with the quoted strings?
Do I need to add CHR(34) before the opening and after closing " of each?
Al Grant!
Chr(39) or " double quote char is the text qualifier to VBA, so you need to do an ajustment to use in the strings.
I presume you have this value anywhere in the worksheet.
So the common way to do this is set the range and use replace to another char, and after all back to chr(39).
If you what to input in hardcode, you will need to concatenate chr(39) with everytime a doublequote appears, or use ""
But the easiest way is to replace find and replace (CTRL+H) to another char, and continue to develop like you was doing
Dim payload As String
payload = payload & Chr(34) & Replace("{'timeframeId':13,'startDate':'2021-05-31 00:00:00.000','endDate':'2021-05-31 00:00:00.000','peopleList':[{'id':123}],", Chr(39), Chr(34)) & Chr(34)
Debug.Print payload
Result:
"{"timeframeId":13,"startDate":"2021-05-31 00:00:00.000","endDate":"2021-05-31 00:00:00.000","peopleList":[{"id":123}],"

How do I pass SQL a double as a parameter?

I'm trying to run this code:
Set Lrs = db.OpenRecordset("Select [LastName]" & _
"From ['Chromebook Registration Form]" & _
"Where [InventoryNumber] = dbInventoryNumber ")
Where "dbInventoryNumber" is a double variable. The field [InventoryNumber] takes a double, but when I run this I get a 3061 Run-time error. Too few arguments. Expected 1.
I know how to pass string variables as parameters, but how do I do it for doubles?
Thanks!
Although the [ ]s will allow the SQL to evaluate, should include space at end of each continued line so SQL string doesn't run together when compiled. Pass double variable same way as string except don't use apostrophe delimiters. (Date/time field parameters use # delimiter.) Don't put variables within quote marks, concatenate them. Remove apostrophe in front of source (assuming this is not really in source name - advise no spaces nor punctuation/special characters in naming convention). Source name that includes word "Form" sounds like name of a form. Source must be a table or query.
Set Lrs = db.OpenRecordset("Select [LastName] " & _
"From [Chromebook Registration Form] " & _
"Where [InventoryNumber] = " & dbInventoryNumber)

How to allow double and single quotes in a string that gets passed to an HTML value attribute?

I have this HTML input that is supposed to allow double and single quotes in the value attribute.
<td><input id="Title" name="Title" class="required" value="$Title$" maxlength="50"/></td>
It gets replaced by this vb.net code:
Dim view As New
StringBuilder(Utils.ReadView("someView.htm"))
With view
.Replace("$Title$", EscapeQuote(model.Widget.Title))
I've been trying to write EscapeQuote to replace all instances of double quotes, with the HTML equivalent & quot;
Private Function EscapeDoubleQuotes(ByVal str As String) As String
str = str.Replace("""", """)
'str = str.Replace(Chr(34), """)
'str = "'" & str & "'"
Return str
End Function
I have also tried using Chr(34) and encasing the entire string in single quotes. My working test case has been a string like "some string".
So in HTML, value=""some string"", which is an empty string, the input box is left blank.
I've also tried single quotes on the HTML attribute.
value='$Title$'
This allows strings enclose in double quotes, but obviously not string enclosed in single quotes.
My head spinning in double quote hell. Any other suggestions I haven't tried?
Instead of trying to encode quotes yourself you can use HttpUtility.HtmlEncode method. It will take care of quotes and all other possible characters invalid in HTML. Example of usage:
Imports System
Imports System.Web
Public Module Module1
Public Sub Main()
Console.Write(HttpUtility.HtmlEncode("""Hello"""))
End Sub
End Module
See it in action: https://dotnetfiddle.net/7fVVh0

How do I preserve spaces in retrieving json keys?

I am using vba-json to parse json and am having trouble preserving spaces in keys. I am new to VBA and didn't see anything in the class to give me the option to preserve spaces in keys.
I am using the class found here
I have:
Function me_()
Dim s, json, i
s = "{'key one':'value one','key two':'value two'}"
Dim lib As New JSONLib
Set json = lib.parse(CStr(s))
For Each i In json
Debug.Print i & "," & json.Item(i)
Next
me_ = "done"
End Function
This preserves the spaces in the values but not the keys:
keyone,value one
keytwo,value two
(jsonlint.com says my json is valid with the spaces in the keys)
It's possible by changing the code, specifically a method parseKey.
Whitespaces (spaces, tabs and various linebreaks) are ignored in keys on line 282:
If InStr(vbCrLf & vbCr & vbLf & vbTab & " ", char) Then

remove unwanted chr(13) from csv string with classic asp (vbscript)

I want to create a classic asp (vbscript) function that replaces all 'returns' that occur between double quotes.
The input string is 'csv' like:
ID;Text;Number
1;some text;20
2;"some text with unwanted return
";30
3;some text again;40
I want to split the string on chr(13) (returns) to create single rows in an array. It works well, except for the unwanted chr(13) that is contained in the text of id 2.
I hope someone could help.
Fundamentally, this is going to be difficult to do as you won't be able to tell whether the carriage return is a valid one or not. Clearly the ones after 20 and 30 are valid.
An approach I would would be to scan through each line in the file and count the commas that occur. If it's less than 3, then append the next line and use the concatenated string. (This of course assumes your CSV structure is consistent and fixed).
What I would really be asking here is why is the CSV like this in the first place? The routine that populates this should really be the one stripping the the CRs out.
Think of a CSV file like a very crude database or spreadsheet. When cosidering the above file, it is clear that the 'Database'/'Spreadsheet' is corrupt.
If the program that generates this is correupting it, then what extent should the reading application goto to correct these defects? I'm not sure that Excel or SQL Server (for example) would go to great lengths to correct a corrupt data source.
Your text file is just like a CSV file but with semicolons not commas. Use ADO to grab the data and it will handle the line breaks in fields.
Specifically (In ASP VBScript):
On Error Resume Next
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001
Set objConnection = Server.CreateObject("ADODB.Connection")
Set objRecordSet = Server.CreateObject("ADODB.Recordset")
strPathtoTextFile = server.mappath(".") 'Path to your text file
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strPathtoTextFile & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
objRecordset.Open "SELECT * FROM test.txt", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
Do Until objRecordset.EOF
Response.Write "ID: " & objRecordset.Fields.Item("ID") & "<br>"
Response.Write "Text: " & objRecordset.Fields.Item("Text") & "<br>"
Response.Write "Number: " & objRecordset.Fields.Item("Number") & "<br>"
objRecordset.MoveNext
Loop
Code sample is modified from Microsofts' Much ADO About Text Files.
This script assumes your data text file is in the same directory as it (the asp file). It also needs a schema.ini file in the same directory as your data text file with the data:
[test.txt]
Format=Delimited(;)
Change text.txt in both code samples above to the name of your text file.
If the unwanted CRLF always occurs inside a text field (inside double quotes), it would not be very difficult to use a regular expression to remove these. Vbscript has a regex engine to its disposal: http://authors.aspalliance.com/brettb/VBScriptRegularExpressions.asp
It all depends ofcourse on how familiar you are with Regular Expressions. I couldn't think of the proper syntax off the top of my head, but this is probably quite easy to figure out.
The solution is pretty easy:
str = "Some text..." & chr(13)
str = REPLACE(str,VbCrlf,"")
The secret is use VbCrlf. For me I use a simple function for solve the problem and add this in my framework.
FUNCTION performStringTreatmentRemoveNewLineChar(byval str)
IF isNull(str) THEN
str = ""
END IF
str = REPLACE(str,VbCrlf,"")
performStringTreatmentRemoveNewLineChar = TRIM(str)
END FUNCTION
Of course this will remove all new lines character from this string. Use carrefully.