<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%> <%Response.ContentType = "text/html; charset=utf-8"%> <% '纳米AI,输出JSON格式 ' 创建数据库连接 Set conn = Server.CreateObject("ADODB.Connection") conn.Open "Provider=SQLOLEDB;Data Source=(local);Initial Catalog=db;User ID=sa;Password=123456;" ' 初始化主数组 Dim resultArr resultArr = Array() ' 查询父类 Set rsParent = conn.Execute("select id,MingCheng from BDClass where ParentID='1' order by orders") If Not rsParent.EOF Then parentData = rsParent.GetRows() ' 循环父类 For i = 0 To UBound(parentData, 2) Dim parentObj, childArr Set parentObj = Server.CreateObject("Scripting.Dictionary") ' 保存父类信息 parentObj.Add "id", parentData(0, i) parentObj.Add "name", parentData(1, i) ' 查询子类 Set rsChild = conn.Execute("select C.Comid,C.Title,C.OutUrl,C.TJtitle,C.Logo,C.ZSstar " & _ "from BDcompany T,Company C " & _ "where T.Comid=C.Comid and C.IsPass=1 " & _ "and T.classid='" & parentData(0, i) & "' " & _ "order by Orders, T.AddTime desc, T.ID desc") ' 初始化子数组 childArr = Array() If Not rsChild.EOF Then childData = rsChild.GetRows() For j = 0 To UBound(childData, 2) Set childObj = Server.CreateObject("Scripting.Dictionary") childObj.Add "comid", childData(0, j) childObj.Add "title", childData(1, j) childObj.Add "outurl", childData(2, j) childObj.Add "tjtitle", childData(3, j) childObj.Add "logo", childData(4, j) childObj.Add "zsstar", childData(5, j) ReDim Preserve childArr(j) Set childArr(j) = childObj Next End If rsChild.Close ' 添加子类到父对象 parentObj.Add "children", childArr ' 添加父对象到主数组 ReDim Preserve resultArr(i) Set resultArr(i) = parentObj Next End If rsParent.Close ' 关闭数据库连接 conn.Close Set conn = Nothing ' 转换为JSON格式输出 Response.ContentType = "application/json" Response.Write("{""data"":" & toJSON(resultArr) & "}") ' 自定义转JSON函数 Function toJSON(data) Dim jsonStr If IsArray(data) Then jsonStr = "[" For Each item In data If TypeName(item) = "Dictionary" Then jsonStr = jsonStr & dictToJSON(item) & "," End If Next If Right(jsonStr, 1) = "," Then jsonStr = Left(jsonStr, Len(jsonStr)-1) jsonStr = jsonStr & "]" Else jsonStr = "null" End If toJSON = jsonStr End Function Function dictToJSON(dict) Dim jsonStr jsonStr = "{" For Each key In dict.Keys value = dict(key) jsonStr = jsonStr & """" & key & """:" If IsArray(value) Then jsonStr = jsonStr & toJSON(value) ElseIf TypeName(value) = "Dictionary" Then jsonStr = jsonStr & dictToJSON(value) Else jsonStr = jsonStr & """" & value & """" End If jsonStr = jsonStr & "," Next If Right(jsonStr, 1) = "," Then jsonStr = Left(jsonStr, Len(jsonStr)-1) dictToJSON = jsonStr & "}" End Function %>