<% '======================================================================================================================= ' JsonLite: small pure-VBScript JSON reader/encoder for request bodies. ' ' Why not G3JSON? Under the AxonASP HTTP server, G3JSON.Parse results and G3DB interfered with each other: parsing before the ' first database open made the first INSERT silently do nothing, and opening the database first made Parse return empty ' dictionaries. Plain VBScript classes avoid native objects altogether (see AGENTS.md). ' ' Set obj = JsonLite_Parse(text) ' Nothing when text is not a valid JSON object ' obj.Exists("Name"), obj.Item("Name") ' JsonLite_Quote(s) ' "text" with JSON escaping ' JsonLite_Num(n) ' locale-independent number literal ' JsonLite_SurrogateSeen ' True after JsonLite_Parse met a backslash-u escape for a UTF-16 surrogate ' ' Speed: on AxonASP every builtin call costs time in proportion to the length of the string it is given (Len, Mid and ' InStr on a 200K string take 0.4-5 ms each), so character loops over a large body are quadratic and timed out. The text ' is therefore split into tokens with ONE call to the AxonASP RegExp engine (JsonLite_Tokens) and the parser walks the ' token array; string tokens are decoded on their own (one Split on the backslash when they contain escapes). ' ' Characters above U+FFFF: on the pinned AxonASP build ChrW(cp > 65535) raises "Invalid procedure call" and a ' surrogate pair is written out as CESU-8 (invalid UTF-8). Surrogate escapes therefore decode to U+FFFD and set ' JsonLite_SurrogateSeen; Api_ReadBody rejects such requests with 422 instead of storing damaged text. ' ' Values: String, Double (numbers), Boolean, Null. Nested objects/arrays are parsed and stored as Null, but the raw ' text of top-level ones is kept: obj.HasRaw(k) / obj.Raw(k) (tokens joined without whitespace); ' JsonLite_ParseStringArray(raw) reads an array of strings, JsonLite_SplitObjectArray(raw) an array of objects. '======================================================================================================================= Class JsonLite_Object Private m_keys(), m_vals(), m_count Private m_rawKeys(), m_rawVals(), m_rawCount Private Sub Class_Initialize() m_count = 0 ReDim m_keys(7) ReDim m_vals(7) m_rawCount = 0 ReDim m_rawKeys(3) ReDim m_rawVals(3) End Sub ' Raw JSON text of a top-level nested object/array value (Item returns Null for those). Public Sub AddRaw(k, rawText) If m_rawCount > UBound(m_rawKeys) Then ReDim Preserve m_rawKeys(m_rawCount * 2) ReDim Preserve m_rawVals(m_rawCount * 2) End If m_rawKeys(m_rawCount) = k m_rawVals(m_rawCount) = rawText m_rawCount = m_rawCount + 1 End Sub Public Function HasRaw(k) Dim i HasRaw = False For i = 0 To m_rawCount - 1 If LCase(m_rawKeys(i)) = LCase(k) Then HasRaw = True Exit Function End If Next End Function Public Function Raw(k) Dim i Raw = Null For i = 0 To m_rawCount - 1 If LCase(m_rawKeys(i)) = LCase(k) Then Raw = m_rawVals(i) Exit Function End If Next End Function Public Sub Add(k, v) Dim i For i = 0 To m_count - 1 If LCase(m_keys(i)) = LCase(k) Then m_vals(i) = v Exit Sub End If Next If m_count > UBound(m_keys) Then ReDim Preserve m_keys(m_count * 2) ReDim Preserve m_vals(m_count * 2) End If m_keys(m_count) = k m_vals(m_count) = v m_count = m_count + 1 End Sub Public Function Exists(k) Dim i Exists = False For i = 0 To m_count - 1 If LCase(m_keys(i)) = LCase(k) Then Exists = True Exit Function End If Next End Function Public Function Item(k) Dim i Item = Null For i = 0 To m_count - 1 If LCase(m_keys(i)) = LCase(k) Then Item = m_vals(i) Exit Function End If Next End Function End Class ' Tokens of a JSON text, in order: strings (with their quotes and escapes), numbers, true/false/null, punctuation, and ' any other single non-whitespace character (which the parser then rejects). Whitespace between tokens is dropped. ' Returns Empty when there is no token. In the pattern the backslash is written \x5C: AxonASP's pattern translation ' rejected a literal backslash inside a character class. Function JsonLite_Tokens(text) Dim re, ms, m, arr, i JsonLite_Tokens = Empty Set re = Server.CreateObject("VBScript.RegExp") re.Global = True re.Pattern = """(?:[^""\x5C]|\x5C.)*""|-?[0-9]+(?:[.][0-9]+)?(?:[eE][+-]?[0-9]+)?|true|false|null|[{}:,]|\x5B|\x5D|[^ \t\r\n]" Set ms = re.Execute("" & text) If ms.Count = 0 Then Exit Function End If ReDim arr(ms.Count - 1) i = 0 For Each m In ms arr(i) = m.Value i = i + 1 Next JsonLite_Tokens = arr End Function ' Raw text of tokens a..b (joined without whitespace) Function JsonLite_JoinTokens(t, a, b) Dim arr, i If b < a Then JsonLite_JoinTokens = "" Exit Function End If ReDim arr(b - a) For i = a To b arr(i - a) = t(i) Next JsonLite_JoinTokens = Join(arr, "") End Function Class JsonLite_Parser Private m_t, m_n, m_i, m_ok, m_sur Public Property Get SurrogateSeen() SurrogateSeen = (m_sur = True) End Property Private Function Load(text) m_sur = False m_ok = True m_i = 0 m_t = JsonLite_Tokens(text) If IsEmpty(m_t) Then m_n = 0 Load = False Else m_n = UBound(m_t) + 1 Load = True End If End Function Private Function Peek() If m_i < m_n Then Peek = m_t(m_i) Else Peek = "" End If End Function Public Function Run(text) Dim obj Set Run = Nothing If Not Load(text) Then Exit Function If m_t(0) <> "{" Then Exit Function Set obj = ReadObject() If Not m_ok Then Exit Function If m_i < m_n Then Exit Function ' trailing garbage Set Run = obj End Function ' Parses text that must be a JSON array of strings. Returns an array of strings, or Null if it is anything else. Public Function RunStringArray(text) Dim items(), n, tok RunStringArray = Null If Not Load(text) Then Exit Function If m_t(0) <> "[" Then Exit Function m_i = 1 n = 0 ReDim items(-1) If Peek() = "]" Then m_i = m_i + 1 If m_i < m_n Then Exit Function RunStringArray = items Exit Function End If Do tok = Peek() If Left(tok, 1) <> """" Then Exit Function ReDim Preserve items(n) items(n) = DecodeString(tok) If Not m_ok Then Exit Function n = n + 1 m_i = m_i + 1 tok = Peek() m_i = m_i + 1 If tok = "]" Then Exit Do If tok <> "," Then Exit Function Loop If m_i < m_n Then Exit Function RunStringArray = items End Function Private Function ReadObject() Dim obj, k, v, tok, rawStart, c0 Set obj = New JsonLite_Object Set ReadObject = obj m_i = m_i + 1 ' { If Peek() = "}" Then m_i = m_i + 1 Exit Function End If Do tok = Peek() If Left(tok, 1) <> """" Then m_ok = False Exit Function End If k = DecodeString(tok) If Not m_ok Then Exit Function m_i = m_i + 1 If Peek() <> ":" Then m_ok = False Exit Function End If m_i = m_i + 1 rawStart = m_i c0 = Peek() v = ReadValue() If Not m_ok Then Exit Function obj.Add k, v If c0 = "{" Or c0 = "[" Then obj.AddRaw k, JsonLite_JoinTokens(m_t, rawStart, m_i - 1) End If tok = Peek() m_i = m_i + 1 If tok = "}" Then Exit Function If tok <> "," Then m_ok = False Exit Function End If Loop End Function ' Reads any value; returns String, Double, Boolean or Null (nested containers are consumed and returned as Null) Private Function ReadValue() Dim tok, c, dummy, lit ReadValue = Null tok = Peek() If Len(tok) = 0 Then m_ok = False Exit Function End If c = Left(tok, 1) If c = """" Then ReadValue = DecodeString(tok) m_i = m_i + 1 ElseIf c = "{" Then Set dummy = ReadObject() ElseIf c = "[" Then SkipArray ElseIf tok = "true" Then ReadValue = True m_i = m_i + 1 ElseIf tok = "false" Then ReadValue = False m_i = m_i + 1 ElseIf tok = "null" Then m_i = m_i + 1 ElseIf (c = "-" And Len(tok) > 1) Or (c >= "0" And c <= "9") Then ' CDbl uses the locale's decimal separator, JSON always uses "." lit = Replace(UCase(tok), ".", Mid(CStr(1.5), 2, 1)) On Error Resume Next ReadValue = CDbl(lit) If Err.Number <> 0 Then Err.Clear m_ok = False End If On Error GoTo 0 m_i = m_i + 1 Else m_ok = False End If End Function Private Sub SkipArray() Dim tok, v m_i = m_i + 1 ' [ If Peek() = "]" Then m_i = m_i + 1 Exit Sub End If Do v = ReadValue() If Not m_ok Then Exit Sub tok = Peek() m_i = m_i + 1 If tok = "]" Then Exit Sub If tok <> "," Then m_ok = False Exit Sub End If Loop End Sub ' Decodes one string token (with its quotes). Without escapes this is a single Mid. With escapes the content is split ' on the backslash: every part after the first starts with an escape character, except that "\\" gives an empty ' part (the escaped backslash), after which the next part is plain text. Private Function DecodeString(tok) Dim inner, parts, out(), i, p, e, h, cu, h2, lo, ub inner = Mid(tok, 2, Len(tok) - 2) If InStr(inner, "\") = 0 Then DecodeString = inner Exit Function End If DecodeString = "" parts = Split(inner, "\") ub = UBound(parts) ReDim out(ub) For i = 0 To ub out(i) = "" Next out(0) = parts(0) i = 1 Do While i <= ub p = parts(i) If Len(p) = 0 Then out(i) = "\" If i + 1 > ub Then m_ok = False ' a lone trailing backslash Exit Function End If out(i + 1) = parts(i + 1) i = i + 2 Else e = Left(p, 1) Select Case e Case """": out(i) = """" & Mid(p, 2) Case "/": out(i) = "/" & Mid(p, 2) Case "b": out(i) = Chr(8) & Mid(p, 2) Case "f": out(i) = Chr(12) & Mid(p, 2) Case "n": out(i) = vbLf & Mid(p, 2) Case "r": out(i) = vbCr & Mid(p, 2) Case "t": out(i) = vbTab & Mid(p, 2) Case "u" h = Mid(p, 2, 4) If Len(h) < 4 Or Not IsHex(h) Then m_ok = False Exit Function End If cu = CLng("&H" & h) ' "&H8000".."&HFFFF" are read as signed 16-bit (e.g. D83D -> -10179) If cu < 0 Then cu = cu + 65536 End If ' A UTF-16 surrogate pair (backslash-u D83D, backslash-u DE00) is one code point above U+FFFF, ' which this runtime cannot hold (see header): consume the pair, flag it, emit U+FFFD. If cu >= 55296 And cu <= 56319 And Len(p) = 5 And i + 1 <= ub Then If Left(parts(i + 1), 1) = "u" Then h2 = Mid(parts(i + 1), 2, 4) If Len(h2) = 4 And IsHex(h2) Then lo = CLng("&H" & h2) If lo < 0 Then lo = lo + 65536 End If If lo >= 56320 And lo <= 57343 Then i = i + 1 p = "u" & h & Mid(parts(i), 6) End If End If End If End If If cu >= 55296 And cu <= 57343 Then m_sur = True cu = 65533 End If out(i) = ChrW(cu) & Mid(p, 6) Case Else m_ok = False Exit Function End Select i = i + 1 End If Loop DecodeString = Join(out, "") End Function Private Function IsHex(h) Dim i, c IsHex = True For i = 1 To Len(h) c = LCase(Mid(h, i, 1)) If Not ((c >= "0" And c <= "9") Or (c >= "a" And c <= "f")) Then IsHex = False Exit Function End If Next End Function End Class ' Array of strings from the raw text of a JSON array, or Null when it is not an array of strings Function JsonLite_ParseStringArray(text) Dim p Set p = New JsonLite_Parser JsonLite_ParseStringArray = p.RunStringArray(text) End Function ' Raw texts of the objects in a JSON array of objects ("[{...},{...}]"), each parseable with JsonLite_Parse. ' Returns an empty array for "[]", Null when the text is not an array whose elements are all objects. ' The text has already been validated as JSON by the body parse, so only depth is tracked (strings are single tokens). Function JsonLite_SplitObjectArray(text) Dim t, n, i, tok, depth, start, items(), cnt JsonLite_SplitObjectArray = Null t = JsonLite_Tokens(text) If IsEmpty(t) Then Exit Function End If n = UBound(t) + 1 If n < 2 Then Exit Function End If If t(0) <> "[" Or t(n - 1) <> "]" Then Exit Function End If cnt = 0 ReDim items(7) depth = 0 start = 0 For i = 1 To n - 2 tok = t(i) If tok = "{" Or tok = "[" Then If depth = 0 Then If tok = "[" Then Exit Function ' a nested array element End If start = i End If depth = depth + 1 ElseIf tok = "}" Or tok = "]" Then depth = depth - 1 If depth = 0 Then If cnt > UBound(items) Then ReDim Preserve items(cnt * 2) End If items(cnt) = JsonLite_JoinTokens(t, start, i) cnt = cnt + 1 End If ElseIf depth = 0 Then If tok <> "," Then Exit Function ' a string/number/true/false/null element End If End If Next If cnt = 0 Then JsonLite_SplitObjectArray = Array() Else ReDim Preserve items(cnt - 1) JsonLite_SplitObjectArray = items End If End Function Dim JsonLite_SurrogateSeen JsonLite_SurrogateSeen = False Function JsonLite_Parse(text) Dim p Set p = New JsonLite_Parser Set JsonLite_Parse = p.Run(text) JsonLite_SurrogateSeen = p.SurrogateSeen End Function ' "text" with JSON escaping (non-ASCII is left as is; the response is UTF-8) ' Built from native Replace calls: a per-character loop with string concatenation was quadratic (seconds per 100 KB). Function JsonLite_Quote(s) Dim t, n t = Replace("" & s, "\", "\\") t = Replace(t, """", "\""") t = Replace(t, ChrW(10), "\n") t = Replace(t, ChrW(13), "\r") t = Replace(t, ChrW(9), "\t") For n = 0 To 31 If n <> 9 Then If n <> 10 Then If n <> 13 Then t = Replace(t, ChrW(n), "\u" & Right("0000" & Hex(n), 4)) End If End If End If Next JsonLite_Quote = """" & t & """" End Function ' Locale-independent number literal (CStr uses the locale's decimal separator) Function JsonLite_Num(n) JsonLite_Num = Replace(CStr(CDbl(n)), ",", ".") End Function %>