asp将数据库里的记录转换成json

<%
'---------------------------------------
' jsonclass类
' 将select语句的执行结果转换成json
'------------------------------------------
class jsonclass
' 定义类属性,默认为private
dim p_sqlstring ' 用于设置select
dim p_root ' 返回的json对象的名称
dim rs,conn

private sub class_initialize()
sqlstring = ""
json = ""
'初始化conn和rs
call initconn(conn)
call initrs(rs)
end sub

private sub class_terminate()
'清除conn和rs
call clearconn(conn)
call clearrs(rs)
end sub

' 可以外部调用的公共方法
public function getjson()
dim rs
dim returnstr
dim i
dim onerecord

' 获取数据
set rs= server.createobject("adodb.recordset")
rs.open sql,conn,1,1
' 生成json字符串
if rs.eof=false and rs.bof=false then
returnstr="{ "&chr(13)& chr(9) & chr(9) & root & ":{ "& chr(13) & chr(9) & chr(9) &chr(9) & chr(9) &"records:[ " & chr(13)

while(not rs.eof)
' -------
onerecord= chr(9) & chr(9) & chr(9) & chr(9) & chr(9) & "{ "

for i=0 to rs.fields.count -1
onerecord=onerecord & chr(34) & rs.fields(i).name&chr(34) &":"
onerecord=onerecord & chr(34) & rs.fields(i).value&chr(34) &","
next
'去除记录最后一个字段后的","
onerecord=left(onerecord,instrrev(onerecord,",")-1)
onerecord=onerecord & "}," & chr(13)
'------------
returnstr=returnstr & onerecord
rs.movenext
wend
' 去除所有记录数组后的","
returnstr=left(returnstr,instrrev(returnstr,",")-1) & chr(13)
returnstr=returnstr & chr(9) & chr(9) &chr(9) & chr(9) &"]" & chr(13) & chr(9) & chr(9) & "}" &chr(13) & "}"
end if
getjson=returnstr
end function

'私用方法,在类中使用
private function check()

end function

'数据库操作
sub initconn(conn)
set conn=server.createobject("adodb.connection")
conn.mode=3
conn.open connstr
end sub

sub clearconn(conn)
conn.close
set conn=nothing
end sub

sub initrs(rs)
set rs=server.createobject("adodb.recordset")
end sub
sub clearrs(rs)
set rs=nothing
end sub

public property get sql
sql = p_sqlstring
end property

public property let sql(value)
p_sqlstring = value
end property

public property get root
root = p_root
end property

public property let root(value)
p_root = value
end property
'
end class
%>
<%
set json = new jsonclass
json.sql = "select * from research_dictionary"
json.root = "research_dictionary"
response.charset="utf-8"
'call output(json.getjson())
%>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值