<%
'假設 JSON 數據
Dim jsonData
jsonData = '{"name":"John","age":30,"hobbies":["reading","coding","gaming"]}'
Function parseJSON(jsonStr)
Dim obj, pair, key, value
Set obj = CreateObject("Scripting.Dictionary")
' 分割鍵值對
Dim matches
Set regEx = New RegExp
regEx.Pattern = """([^""]+)""\s*:\s*(.+?)(?=\s*,\s*""[^""]+""\s*:\s*|$)'
Set matches = regEx.Execute(jsonStr)
For Each match In matches
pair = match.SubMatches
key = pair(0)
value = pair(1)
' 處理字符串值
If Left(value, 1) = """' And Right(value, 1) = """ Then
value = Mid(value, 2, Len(value) - 2)
End If
' 處理數字值
If IsNumeric(value) Then
value = CDbl(value)
End If
' 處理布爾值
If value = "true" Then
value = True
ElseIf value = "false" Then
value = False
End If
' 處理數組
If Left(value, 1) = "[" And Right(value, 1) = "]" Then
value = parseArray(value)
End If
' 處理對象
If Left(value, 1) = "{" And Right(value, 1) = "}" Then
value = parseJSON(value)
End If
obj.Add key, value
Next
Set parseJSON = obj
End Function
Function parseArray(arrStr)
Dim arr, item
Set arr = CreateObject("Scripting.Dictionary")
Dim index = 0
' 分割數組元素
Dim matches
Set regEx = New RegExp
regEx.Pattern = "\s*(.+?)\s*(?=\s*,\s*|$)"
Set matches = regEx.Execute(arrStr)
For Each match In matches
item = match.SubMatches(0)
' 處理字符串值
If Left(item, 1) = """' And Right(item, 1) = """ Then
item = Mid(item, 2, Len(item) - 2)
End If
' 處理數字值
If IsNumeric(item) Then
item = CDbl(item)
End If
' 處理布爾值
If item = "true" Then
item = True
ElseIf item = "false" Then
item = False
End If
' 處理數組
If Left(item, 1) = "[" And Right(item, 1) = "]" Then
item = parseArray(item)
End If
' 處理對象
If Left(item, 1) = "{" And Right(item, 1) = "}" Then
item = parseJSON(item)
End If
arr.Add index, item
index = index + 1
Next
Set parseArray = arr.Items
End Function
' 解析 JSON
Set parsedObj = parseJSON(jsonData)
' 輸出結果
Response.Write("Name: " & parsedObj("name") & "<br>")
Response.Write("Age: " & parsedObj("age") & "<br>")
Dim hobby
For Each hobby In parsedObj("hobbies")
Response.Write("Hobby: " & hobby & "<br>")
Next
Set parsedObj = Nothing
%>