背景:
近期帮一个公司做第三方API的二次封装,需要部署到该公司网站。所获取的是Json数据格式。由于该公司原系统采用的ASP+VBS技术方案,因此采用VBS对API进行请求、封装。
实现:
废话不多说,直接上代码。由于某些原因,不能将所有代码贴出来,有问题的可以留言。
<!--#include file="LibJson.asp"--> <script Language="jscript" runat="server">
Array.prototype.get = function(x) { return this[x]; };
function parseJSON(strJSON) { return eval("(" + strJSON + ")"); }
</script> <% Sub writeData()
Set My = MoLibJson.new() My.dateformat = "yyyy-MM-dd HH:mm:ss"
My.put "status","ok"
My.put "time",Now Set results = My.put("result")
results.datatype="array" Set writetoResult = Server.CreateObject("Scripting.FileSystemObject") writetoResult.CreateTextFile ResultPh,true Set resufile = writetoResult.OpenTextFile(ResultPh,,True)
resufile.Write My.toString()
Set resufile = Nothing End Sub Sub getDataByLocation (longitude,latitude)
URL = “http:xxxx.com/xx.json”
weatherData = GetHttpPage(URL,"UTF-8") 'Http请求,获取返回的json数据
Set obj = parseJSON(weatherData) ‘对获取到的json数据进行解析 ‘生成json数据
Set result1 = results.put()
result1.put "location",array(longitude,latitude),"vbarray" Set subPre = result1.put("precipitation")
Set preHou = subPre.put("hourly")
preHou.datatype="array"
Set hou= obj.result.hourly.precipitation
For n= To
Set kvHou = preHou.put()
kvHou.put "value",hou.get(n).value
kvHou.put "datetime",hou.get(n).datetime
Next Dim arrayData()
Set minu= obj.result.minutely.precipitation
For n= To
arrayData(n)= minu.get(n)
Next
subPre.put "minutely",arrayData,"vbarray" End Sub Function GetHttpPage(url, charset)
Dim http
Set http = Server.createobject("Msxml2.ServerXMLHTTP")
'Set http = Server.createobject("MSXML2.XMLHTTP.6.0")
'set http = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")
http.setOption() =
http.Open "GET", url, false
http.Send()
If http.readystate<> Then
Exit Function
End If
GetHttpPage = BytesToStr(http.ResponseBody, charset)
Set http = Nothing
End function Function BytesToStr(body, charset)
Dim objStream
Set objStream = Server.CreateObject("Adodb.Stream")
objStream.Type =
objStream.Mode =
objStream.Open
objStream.Write body
objStream.Position =
objStream.Type =
objStream.Charset = charset
BytesToStr = objStream.ReadText
objStream.Close
Set objStream = Nothing
End Function %>
LibJson.asp.
这个代码是用的别人的,可以直接用
<script language="jscript" runat="server">
/*'by anlige at www.9fn.net*/
function MoLibJson(t,df){
this.table=[];
this.datatype=t||"object";
this.dateformat=df||"";
}
MoLibJson.New = function(t,df){return new MoLibJson(t,df);};
MoLibJson.prototype.put=function(key,value,tp){
if(value===undefined)return this.putnew(key||"TMP__");
tp = tp||"";
tp = tp.toLowerCase();
if(tp=="vbarray" || this.IsVBArray(value))return this.putvbarray(key,value);
if(tp=="arraylist")return this.put(key,value.split(","));
if(tp=="dictionary" || this.IsDictionary(value))return this.putdictionary(key,value);
if(tp=="rows" || this.IsRecordset(value))return this.putrows(key,value);
this.table.push({key:key,value:value});
return this.table[this.table.length-];a
};
MoLibJson.prototype.putdictionary=function(key,value){
return this.putnew(key).fromdictionary(value);
};
MoLibJson.prototype.fromdictionary=function(value){
if(value.count<=)return obj;
var keys=(new VBArray(value.keys())).toArray();
for(var i =;i<keys.length;i++){
this.put(keys[i],value.item(keys[i]));
}
return this;
};
MoLibJson.prototype.putnew=function(key){
return this.put(key,new MoLibJson("object",this.dateformat))['value'];
};
MoLibJson.prototype.putnewarray=function(key){
return this.put(key,new MoLibJson("array",this.dateformat))['value'];
};
MoLibJson.prototype.putvbarray=function(key,value){
return this.put(key,(new VBArray(value)).toArray());
};
MoLibJson.prototype.putrows=function(key,rs,pagesize){
return this.putnewarray(key).fromrows(rs,pagesize);
};
MoLibJson.prototype.fromrows=function(rs,pagesize){
this.datatype="array";
if(pagesize==undefined)pagesize=-;
var ps = rs.Bookmark;
var k=;
while(!rs.eof && (k<pagesize || pagesize==-)){
k++;
var tmp__=new Object();
for(var i=;i<rs.fields.count;i++){
tmp__[rs.fields(i).Name]=rs.fields(i).value;
}
this.put("",tmp__);
rs.MoveNext();
}
try{
rs.Bookmark=ps;
}catch(ex){}
return this;
};
MoLibJson.prototype.toString = MoLibJson.prototype.getobjectstring=function(key){
key=key||"";
if(this.datatype=="array"){
if(this.table.length<=)return "[]";
var ret="[";
for(var i=;i<this.table.length;i++){
ret+=this.parse(this.table[i]["value"]) + ",";
}
if(ret!="[")ret=ret.substr(,ret.length-);
ret+="]";
if(key!="")return "{\"" + key + "\":" + ret + "}";
return ret;
}else{
if(this.table.length<=)return "{}";
var ret="{";
for(var i=;i<this.table.length;i++){
ret+="\""+this.table[i]["key"]+"\":" + this.parse(this.table[i]["value"]) + ",";
}
if(ret!="{")ret=ret.substr(,ret.length-);
ret+="}";
if(key!="")return "{\"" + key + "\":" + ret + "}";
return ret;
}
};
MoLibJson.prototype.del=function(key){
if(this.table.length<=)return;
var tb = [],find=false;
for(var i=;i<this.table.length;i++){
if(this.table[i]["key"]!=key){
tb.push(this.table[i]);
}else{
find = true;
}
}
if(find)this.table = tb;
};
MoLibJson.prototype.set=function(key,value){
this.del(key);
this.put(key,value);
};
MoLibJson.prototype.parse=function(value){
if(value===null)return "null";
if(this.IsVBArray(value))value=(new VBArray(value)).toArray();
var ty = typeof(value);
if(ty=="string"){
return "\"" + this.encode(value) + "\"";
}else if(ty=="number" || ty=="boolean"){
return value;
}else if(ty=="date"){
var dt = new Date(value);
if(this.dateformat==""){
return "\""+dt.toString()+"\"";
}else{
return "\""+this.formatdate(value,this.dateformat)+"\"";
}
}else if(ty=="object"){
if(value.constructor){
if(value.constructor==Array){
var ret1="[";
for(var j=;j<value.length;j++){
ret1+=this.parse(value[j])+",";
}
if(ret1!="[")ret1=ret1.substr(,ret1.length-);
ret1+="]";
return ret1;
}else if(value.constructor==MoLibJson){
return value.getobjectstring();
}else if(value.constructor==Object){
var o = new MoLibJson("object",this.dateformat);
for(var i in value){
if(value.hasOwnProperty && value.hasOwnProperty(i)) o.put(i,value[i]);
}
return o.getobjectstring();
}else if(value.constructor==Date){
var dt = new Date(value);
if(this.dateformat==""){
return "\""+dt.toString()+"\"";
}else{
return "\""+this.formatdate(value,this.dateformat)+"\"";
}
}else{
return this.encode(value.constructor.toString());
}
}
}
return "\"unknown:" + ty +"\"";
};
MoLibJson.prototype.formatstring=function(src,format){
if(!/^(left|right)\s(\d+)$/i.test(format))return src;
var direction = /^(left|right)\s(\d+)$/i.exec(format)[];
var len = parseInt(/^(left|right)\s(\d+)$/i.exec(format)[]);
if(direction=="left")return src.substr(,len);
if(direction=="right")return src.substr(src.length-len,len);
};
MoLibJson.prototype.formatdate=function(dt,formatStr){
if(typeof dt!="date")dt=new Date();
dt = new Date(dt);
var y=new Array(),m=new Array(),d=new Array(),h=new Array(),n=new Array(),s=new Array(),w,ws=new Array(),t = new Array(),H=new Array();
y[] = dt.getFullYear();
m[] = dt.getMonth()+;
d[] = dt.getDate();
h[] = dt.getHours();
H[] = h[] % ;
n[] = dt.getMinutes();
s[] = dt.getSeconds();
y[] = y[];
m[] = this.formatstring("" +m[],"right 2");
d[] = this.formatstring("" +d[],"right 2");
h[] = this.formatstring("" +h[],"right 2");
H[] = this.formatstring("" +H[],"right 2");
n[] = this.formatstring("" +n[],"right 2");
s[] = this.formatstring("" +s[],"right 2");
ws[] = "日,一,二,三,四,五,六".split(",");
ws[] = "Sun,Mon,Tues,Wed,Thur,Fri,Sat".split(",");
t[] = dt.getMilliseconds();
w=dt.getDay()-; var returnStr;
returnStr = formatStr.replace(/yyyy/g,y[]);
returnStr = returnStr.replace(/yy/g,y[]);
returnStr = returnStr.replace(/MM/g,m[]);
returnStr = returnStr.replace(/M/g,m[]);
returnStr = returnStr.replace(/dddd/g,ws[][w]);
returnStr = returnStr.replace(/ddd/g,ws[][w]);
returnStr = returnStr.replace(/dd/g,d[]);
returnStr = returnStr.replace(/d/g,d[]);
returnStr = returnStr.replace(/HH/g,h[]);
returnStr = returnStr.replace(/H/g,h[]);
returnStr = returnStr.replace(/mm/g,n[]);
returnStr = returnStr.replace(/m/g,n[]);
returnStr = returnStr.replace(/ss/g,s[]);
returnStr = returnStr.replace(/s/g,s[]);
returnStr = returnStr.replace(/tttt/g,t[]);
return returnStr ;
};
MoLibJson.prototype.encode=function(str){
if(str==undefined) return "";
if(str=="")return "";
var i, j, aL1, aL2, c, p,ret="";
aL1 = Array(0x22, 0x5C, 0x2F, 0x08, 0x0C, 0x0A, 0x0D, 0x09);
aL2 = Array(0x22, 0x5C, 0x2F, 0x62, 0x66, 0x6E, 0x72, 0x74);
for(i = ;i<str.length;i++){
p = true;
c = str.substr(i,);
for(j = ;j<=;j++){
if(c == String.fromCharCode(aL1[j])){
ret += "\\" + String.fromCharCode(aL2[j]);
p = false;
break;
}
}
if(p){
var a = c.charCodeAt();
if(a > && a < ){
ret +=c
}else if(a > - || a < ){
var slashu = a.toString();
while(slashu.length<){slashu=""+slashu;}
ret += "\\u" + slashu;
}
}
}
return ret;
};
MoLibJson.prototype.IsDictionary=function(o) {
return ((o != null) &&
(typeof(o) == "object") &&
(o instanceof ActiveXObject) &&
(typeof(o.Add) == "unknown") &&
(typeof(o.Exists) == "unknown") &&
(typeof(o.Items) == "unknown") &&
(typeof(o.Keys) == "unknown") &&
(typeof(o.Remove) == "unknown") &&
(typeof(o.RemoveAll) == "unknown") &&
(typeof(o.Count) == "number") &&
(typeof(o.Item) == "unknown") &&
(typeof(o.Key) == "unknown"));
}; MoLibJson.prototype.IsVBArray=function(o) {
return ((o != null) &&
(typeof(o) == "unknown") &&
(o.constructor == VBArray) &&
(typeof(o.dimensions) == "function") &&
(typeof(o.getItem) == "function") &&
(typeof(o.lbound) == "function") &&
(typeof(o.toArray) == "function") &&
(typeof(o.ubound) == "function"));
}
MoLibJson.prototype.IsRecordset=function(o) {
return ((o != null) &&
(typeof(o) == "object") &&
(o instanceof ActiveXObject) &&
(typeof(o.Fields) == "object") &&
(typeof(o.CursorType) == "number") &&
(typeof(o.LockType) == "number") &&
(typeof(o.BookMark) == "number") &&
(typeof(o.AbsolutePage) == "number" || typeof(o.AbsolutePage) == "unknown") &&
(typeof(o.Recordcount) == "number" || typeof(o.Recordcount) == "unknown") &&
(typeof(o.PageSize) == "number"));
}
</script>