asp将数组for循环输出json格式

ASP   2025-02-26 16:39   58   0  
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
    ' 定义数据数组
    Dim cities
    cities = Array(_
        Dictionary("id", 1, "title", "北京", "caption", "首都"), _
        Dictionary("id", 2, "title", "合肥", "caption", "省会"), _
        Dictionary("id", 3, "title", "重庆", "caption", "直辖市") _
    )

    ' 开始输出 JSON 数组格式
    Response.Write("[" & vbCrLf)

    ' 循环输出每个字典项
    Dim city
    For Each city In cities
        Response.Write("    {" & vbCrLf)
        Response.Write("        ""id"": " & city("id") & "," & vbCrLf)
        Response.Write("        ""title"": """ & city("title") & """," & vbCrLf)
        Response.Write("        ""caption"": """ & city("caption") & """" & vbCrLf)
        ' 判断是否是最后一个元素,避免输出多余的逗号
        If city Is cities(UBound(cities)) Then
            Response.Write("    }")
        Else
            Response.Write("    },")
        End If
        Response.Write(vbCrLf)
    Next

    ' 结束 JSON 数组格式
    Response.Write("]")

' 定义一个辅助函数来创建字典
Function Dictionary(key1, value1, key2, value2, key3, value3)
    Dim dict
    Set dict = CreateObject("Scripting.Dictionary")
    dict.Add key1, value1
    dict.Add key2, value2
    dict.Add key3, value3
    Set Dictionary = dict
End Function
%>


博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。