ASP rs记录集转JSON

将asp的rs记录集,转换为Json,但是,行数多了非常慢! 保存为Json.asp

复制代码
  1 <%
  2 '**********************************************************************************************
  3 '* GAB_LIBRARY Copyright (C) 2003 - This file is part of GAB_LIBRARY       
  4 '* For license refer to the license.txt                                       
  5 '***********************************************************************************************
  6 
  7 '****************************************************************************************
  8 
  9 '' @CLASSTITLE:        JSON
 10 '' @CREATOR:        Michal Gabrukiewicz (gabru at grafix.at), Michael Rebec
 11 '' @CONTRIBUTORS:    - Cliff Pruitt (opensource at crayoncowboy.com)
 12 ''                    - Sylvain Lafontaine
 13 '' @CREATEDON:        2007-04-26 12:46
 14 '' @CDESCRIPTION:    Comes up with functionality for JSON (http://json.org) to use within ASP.
 15 ''                     Correct escaping of characters, generating JSON Grammer out of ASP datatypes and structures
 16 '' @REQUIRES:        -
 17 '' @OPTIONEXPLICIT:    yes
 18 '' @VERSION:        1.4
 19 
 20 '****************************************************************************************
 21 class JSON
 22 
 23 'private members
 24 private output, innerCall
 25 
 26 'public members
 27 public toResponse        ''[bool] should generated results be directly written to the response? default = false
 28 
 29 '*********************************************************************************
 30 '* constructor
 31 '*********************************************************************************
 32 public sub class_initialize()
 33         newGeneration()
 34         toResponse = false
 35 end sub
 36 
 37 '******************************************************************************************
 38 '' @SDESCRIPTION:    STATIC! takes a given string and makes it JSON valid
 39 '' @DESCRIPTION:    all characters which needs to be escaped are beeing replaced by their
 40 ''                    unicode representation according to the
 41 ''                    RFC4627#2.5 - http://www.ietf.org/rfc/rfc4627.txt?number=4627
 42 '' @PARAM:            val [string]: value which should be escaped
 43 '' @RETURN:            [string] JSON valid string
 44 '' asc 函数被替换成ascw函数以便支持中文
 45 '******************************************************************************************
 46 public function escape(val)
 47 dim cDoubleQuote, cRevSolidus, cSolidus
 48         cDoubleQuote = &h22
 49         cRevSolidus = &h5C
 50         cSolidus = &h2F
 51 
 52 dim i, currentDigit
 53 for i = 1 to (len(val))
 54             currentDigit = mid(val, i, 1)
 55 if ascw(currentDigit) > &h00 and ascw(currentDigit) < &h1F then
 56                 currentDigit = escapequence(currentDigit)
 57 elseif ascw(currentDigit) >= &hC280 and ascw(currentDigit) <= &hC2BF then
 58                 currentDigit = "\u00" + right(padLeft(hex(asc(currentDigit) - &hC200), 2, 0), 2)
 59 elseif ascw(currentDigit) >= &hC380 and ascw(currentDigit) <= &hC3BF then
 60                 currentDigit = "\u00" + right(padLeft(hex(ascw(currentDigit) - &hC2C0), 2, 0), 2)
 61 else
 62 select case ascw(currentDigit)
 63 case cDoubleQuote: currentDigit = escapequence(currentDigit)
 64 case cRevSolidus: currentDigit = escapequence(currentDigit)
 65 case cSolidus: currentDigit = escapequence(currentDigit)
 66 end select
 67 end if
 68             escape = escape & currentDigit
 69 next
 70 end function
 71 
 72 '******************************************************************************
 73 '' @SDESCRIPTION:    generates a representation of a name value pair in JSON grammer
 74 '' @DESCRIPTION:    the generation is done fully recursive so the value can be a complex datatype as well. e.g.
 75 ''                    toJSON("n", array(array(), 2, true), false) or toJSON("n", array(RS, dict, false), false), etc.
 76 '' @PARAM:            name [string]: name of the value (accessible with javascript afterwards). leave empty to get just the value
 77 '' @PARAM:            val [variant], [int], [float], [array], [object], [dictionary], [recordset]: value which needs
 78 ''                    to be generated. Conversation of the data types (ASP datatype -> Javascript datatype):
 79 ''                    NOTHING, NULL -> null, ARRAY -> array, BOOL -> bool, OBJECT -> name of the type,
 80 ''                    MULTIDIMENSIONAL ARRAY -> generates a 1 dimensional array (flat) with all values of the multidim array
 81 ''                    DICTIONARY -> valuepairs. each key is accessible as property afterwards
 82 ''                    RECORDSET -> array where each row of the recordset represents a field in the array.
 83 ''                    fields have properties named after the column names of the recordset (LOWERCASED!)
 84 ''                    e.g. generate(RS) can be used afterwards r[0].ID
 85 ''                    INT, FLOAT -> number
 86 ''                    OBJECT with reflect() method -> returned as object which can be used within JavaScript
 87 '' @PARAM:            nested [bool]: is the value pair already nested within another? if yes then the {} are left out.
 88 '' @RETURN:            [string] returns a JSON representation of the given name value pair
 89 ''                    (if toResponse is on then the return is written directly to the response and nothing is returned)
 90 '*******************************************************************************************
 91 public function toJSON(name, val, nested)
 92 if not nested and not isEmpty(name) then write("{")
 93 if not isEmpty(name) then write("""" & escape(name) & """: ")
 94         generateValue(val)
 95 if not nested and not isEmpty(name) then write("}")
 96         toJSON = output
 97 
 98 if innerCall = 0 then newGeneration()
 99 end function
100 
101 '*********************************************************************************
102 '* generate
103 '******************************************************************************
104 private function generateValue(val)
105 if isNull(val) then
106             write("null")
107 elseif isArray(val) then
108             generateArray(val)
109 elseif isObject(val) then
110 if val is nothing then
111                 write("null")
112 elseif typename(val) = "Dictionary" then
113                 generateDictionary(val)
114 elseif typename(val) = "Recordset" then
115                 generateRecordset(val)
116 else
117                 generateObject(val)
118 end if
119 else
120 'bool
121             varTyp = varType(val)
122 if varTyp = 11 then
123 if val then write("true") else write("false")
124 'int, long, byte
125 elseif varTyp = 2 or varTyp = 3 or varTyp = 17 or varTyp = 19 then
126                 write(cLng(val))
127 'single, double, currency
128 elseif varTyp = 4 or varTyp = 5 or varTyp = 6 or varTyp = 14 then
129                 write(replace(cDbl(val), ",", "."))
130 else
131                 write("""" & escape(val & "") & """")
132 end if
133 end if
134         generateValue = output
135 end function
136 
137 '*****************************************************************************
138 '* generateArray
139 '*****************************************************************************
140 private sub generateArray(val)
141 dim item, i
142         write("[")
143         i = 0
144 'the for each allows us to support also multi dimensional arrays
145 for each item in val
146 if i > 0 then write(",")
147             generateValue(item)
148             i = i + 1
149 next
150         write("]")
151 end sub
152 
153 '*********************************************************************************
154 '* generateDictionary
155 '**************************************************************************
156 private sub generateDictionary(val)
157 dim keys, i
158         innerCall = innerCall + 1
159         write("{")
160         keys = val.keys
161 for i = 0 to uBound(keys)
162 if i > 0 then write(",")
163             toJSON keys(i), val(keys(i)), true
164 next
165         write("}")
166         innerCall = innerCall - 1
167 end sub
168 
169 '*******************************************************************
170 '* generateRecordset
171 '*******************************************************************
172 private sub generateRecordset(val)
173 dim i
174         write("[")
175 while not val.eof
176             innerCall = innerCall + 1
177             write("{")
178 for i = 0 to val.fields.count - 1
179 if i > 0 then write(",")
180                 toJSON lCase(val.fields(i).name), val.fields(i).value, true
181 next
182             write("}")
183             val.movenext()
184 if not val.eof then write(",")
185             innerCall = innerCall - 1
186 wend
187         write("]")
188 end sub
189 
190 '*******************************************************************************
191 '* generateObject
192 '*******************************************************************************
193 private sub generateObject(val)
194 dim props
195 on error resume next
196 set props = val.reflect()
197 if err = 0 then
198 on error goto 0
199             innerCall = innerCall + 1
200             toJSON empty, props, true
201             innerCall = innerCall - 1
202 else
203 on error goto 0
204             write("""" & escape(typename(val)) & """")
205 end if
206 end sub
207 
208 '*******************************************************************************
209 '* newGeneration
210 '*******************************************************************************
211 private sub newGeneration()
212         output = empty
213         innerCall = 0
214 end sub
215 
216 '*******************************************************************************
217 '* JsonEscapeSquence
218 '*******************************************************************************
219 private function escapequence(digit)
220         escapequence = "\u00" + right(padLeft(hex(asc(digit)), 2, 0), 2)
221 end function
222 
223 '*****************************************************************************
224 '* padLeft
225 '*****************************************************************************
226 private function padLeft(value, totalLength, paddingChar)
227         padLeft = right(clone(paddingChar, totalLength) & value, totalLength)
228 end function
229 
230 '*****************************************************************************
231 '* clone
232 '******************************************************************************************
233 public function clone(byVal str, n)
234 dim i
235 for i = 1 to n : clone = clone & str : next
236 end function
237 
238 '******************************************************************************************
239 '* write
240 '******************************************************************************************
241 private sub write(val)
242 if toResponse then
243             response.write(val)
244 else
245             output = output & val
246 end if
247 end sub
248 
249 end class
250 %> 
View Code
复制代码

 

引入Json.asp文件,生成Json

复制代码
 1         sql="1=1"
 2         
 3         
 4         if empname<>"" then 
 5         sql=sql&" and empname like '%"&empname&"%'  "
 6         end if
 7         
 8         if dptid<>"" then 
 9         sql=sql&" and dptid like '%"&dptid&"%'  "
10         end if
11         
12         if deptid<>0 then 
13         sql=sql&" and deptid = '"&deptid&"'  "
14         end if
15 
16         
17     sql="select id,gzdat,deptid,dptid,empid,empname,depname,empbiaos,gz_all from empgz where "&sql&" and gzdat = '"&dates&"'   "
18     Set Rs = Server.CreateObject("ADODB.Recordset")      
19     Rs.Open sql,conn,1,3 
20     jsonStr = ""
21     rows = ""
22 
23     Dim i,json_rows,json_ret,arr_rows
24     Dim myArray()
25     Redim myArray(rs.recordcount-1) '将数组大小重新定义为20
26     Set jsonObj=New json
27     jsonObj.toResponse=False
28     Set json_ret = server.createobject("scripting.dictionary")        
29     For i=0 To rs.recordcount-1
30         Set myArray(i) = server.createobject("scripting.dictionary")
31         For Each e In rs.Fields                
32                 'rows = rows &""""& e.Name & """:""" & replace(e.value,chr(34),"@_'_@") & """," 
33                 myArray(i).Add e.Name,e.value  '将key/value加到行数组对象中
34         Next   
35         Rs.movenext
36     Next       
37     json_ret.Add "total",rs.recordcount
38     json_ret.Add "rows",myArray 
39     jsonStr = jsonObj.toJSON(Empty,json_ret,False)
40 
41 
42     'JsStr = jsonObj.toJSON(Empty,myArray,False)
43     
44     response.Write jsonStr
View Code
复制代码

 

具体效果:

{"total": 4,"rows": [

{"id": 216686,"gzdat": "202106","deptid": "009","dptid": "长治淮海店","empid": 12451,"empname": "魏红","depname": "OTC区","empbiaos": "三星级执业药师质管验收","gz_all": 4463.33},

{"id": 216687,"gzdat": "202106","deptid": "009","dptid": "长治淮海店","empid": 14165,"empname": "李志娟","depname": "OTC区","empbiaos": "营业员","gz_all": 2114.75},

{"id": 216688,"gzdat": "202106","deptid": "009","dptid": "长治淮海店","empid": 12616,"empname": "靳韶泽","depname": "管理人员","empbiaos": "店长","gz_all": 4531.45},

{"id": 216689,"gzdat": "202106","deptid": "009","dptid": "长治淮海店","empid": 10748,"empname": "桑仙凤","depname": "管理人员","empbiaos": "客服经理兼验收兼养护","gz_all": 2460.93}

]

}

posted @   茶叶蛋蛋  阅读(157)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示