asp将数组for循环输出json格式
ASP
2025-02-26 16:35
34
0
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
' 定义数据数组
Dim data
data = Array( _
CreateObject("Scripting.Dictionary"), _
CreateObject("Scripting.Dictionary"), _
CreateObject("Scripting.Dictionary") _
)
' 填充数据
data(0).Add "id", 1
data(0).Add "title", "北京"
data(0).Add "caption", "首都"
data(1).Add "id", 2
data(1).Add "title", "合肥"
data(1).Add "caption", "省会"
data(2).Add "id", 3
data(2).Add "title", "重庆"
data(2).Add "caption", "直辖市"
' 设置响应类型为JSON
Response.ContentType = "application/json"
' 初始化JSON字符串
Dim jsonString
jsonString = "["
' 循环遍历数据并构建JSON字符串
Dim i
For i = 0 To UBound(data)
jsonString = jsonString & "{"
jsonString = jsonString & """id"" : " & data(i)("id") & ","
jsonString = jsonString & """title"" : """ & data(i)("title") & ""","
jsonString = jsonString & """caption"" : """ & data(i)("caption") & """"
jsonString = jsonString & "}"
' 如果不是最后一个元素,添加逗号
If i < UBound(data) Then
jsonString = jsonString & ","
End If
Next
' 结束JSON数组
jsonString = jsonString & "]"
' 输出JSON字符串
Response.Write jsonString
%>