建站代码网

热门标签

ASP读取、解析JSON数据

第一种Jscript方式:

<script language="jscript" runat="server">  
    Array.prototype.get = function(x) { return this[x]; };  
    function parseJSON(strJSON) { return eval("(" + strJSON + ")"); }  
    </script>  
    <%  
    Dim json, obj  
    json = "{a:""aaa"", b:{ name:""bb"", value:""text"" }, c:[""item0"", ""item1"", ""item2""]}"  
    Set obj = parseJSON(json)  
      
    Response.Write obj.a & "<br />"  
    Response.Write obj.b.name & "<br />"  
    Response.Write obj.c.length & "<br />"  
    Response.Write obj.c.get(0) & "<br />"  
      
    Set obj = Nothing  
    %>


第二种间接采用Jscript方式:

Dim scriptCtrl  
    Function parseJSON(str)  
        If Not IsObject(scriptCtrl) Then  
            Set scriptCtrl = Server.CreateObject("MSscriptControl.scriptControl")  
            scriptCtrl.Language = "Jscript"  
            scriptCtrl.AddCode "Array.prototype.get = function(x) { return this[x]; }; var result = null;"  
        End If  
        scriptCtrl.ExecuteStatement "result = " & str & ";"  
        Set parseJSON = scriptCtrl.CodeObject.result  
    End Function  
      
    Dim json  
    json = "{a:""aaa"", b:{ name:""bb"", value:""text"" }, c:[""item0"", ""item1"", ""item2""]}"  
      
    Set obj = parseJSON(json)  
      
    Response.Write obj.a & "<br />"  
    Response.Write obj.b.name & "<br />"  
    Response.Write obj.c.length & "<br />"  
    Response.Write obj.c.get(0) & "<br />"  
      
    Set obj = Nothing  
      

    Set scriptCtrl = Nothing


第三种方法:

<%@LANGUAGE="VBscript" CODEPAGE="65001"%>
 <% 
 response.charset="utf-8"
session.codepage=65001 
%>

<script language="Jscript" runat="Server">
function ToObject(json) {
    var o;
    eval("o=" + json);
    return o;
}
function toArray(s){
    var dic = Server.CreateObject("scripting.Dictionary")
    eval("var a=" + json);
    for(var i=0;i<a.length;i++){
        var obj = Server.CreateObject("scripting.Dictionary")
        for(x in a[i]) obj.Add(x,a[i][x])
        dic.Add(i, obj);
    }
    return dic
}
</script>
<%
json = "[{""date"":""周四 08月07日 (实时:2)"",""weather"":""晴"",""wind"":""微风"",""temperature"":""21""},{""date"":""周五"",""weather"":""多云"",""wind"":""微风"",""temperature"":""31 ~ 22""},{""date"":""周六"",""weather"":""多云转阴"",""wind"":""微风"",""temperature"":""30 ~ 22""},{""date"":""周日"",""weather"":""阴转晴"",""wind"":""微风"",""temperature"":""31 ~ 22""}]"
 
Set ob = toArray(json)
For i=0 To ob.Count-1
  Response.Write ob(i)("date") & " " 
next
 
Set ob = Nothing
%>
 

</body>
</html>



X