经典ASP:如何使用AXE JSON实现一个RecordSet转换成JSON符号 [英] Classic ASP: how to convert a RecordSet to json notation using AXE json implementation

查看:892
本文介绍了经典ASP:如何使用AXE JSON实现一个RecordSet转换成JSON符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做使用jQuery和其他一些工具AJAX的应用程序,并在一些部分我想用一个传统的ASP后台检索与阿贾克斯的数据,我看到了存在于AXE一个很好的实施JS​​ON类(ASP至尊版)框架,我用它,但现在我不知道如何使用它做好。

修改:根据正确答案的<一个href=\"http://stackoverflow.com/questions/5328858/json-stringify-fails-on-scripting-dictionary-objects\">JSON.Stringify对失败的Scripting.Dictionary对象主题,我决定做一个自定义的函数来处理记录集。

编辑2:现在我失去了价值数据时调用的 JSON.stringify 的里面的功能JSONStringify(对象)

当记录作为价值传递给的 JSONStringify 的一切都很好,但是当的 JSON.stringify 的执行,在的参数,该参数必须包含该记录成为的未定义

什么我期待(例如)

传递一个记录集从一个SQL查询 SELECT姓名,电话用户的一看到这样的输出

  [
    {名:Jonh史密斯,电话:12345678},
    {名:四月迈克尔逊,电话:77788802},
    ...
]

传递一个字典,看到类似的基于在字典中声明的元素的东西。

  {
   中element1:值1
   在element2:VALUE2
   元素3:值3
   元素4:值4,
   元素5:值5
}

如果我愿意支持其他类型的对象,我可以做到这一点扩展功能

来源$ C ​​$ C

getcatalogos.asp

 &LT;! - #include文件=../包括/ conexion.asp - &GT;
&LT;! - #include文件=../包括/ json2.asp - &GT;
&LT;! - #include文件=../包括/ JSON-字符串化-parser.asp - &GT;
&LT;%
Response.ContentType =应用/ JSON
暗淡aVals(2)功能getCatalogo(TIPO,则params)
    暗淡oConn,oCmd,sSQL,口服补液盐,CONT2
    暗淡ADATA,OPAR,续
    昏暗的信息    设置oConn =的Server.CreateObject(ADODB.Connection)
    设置oCmd =的Server.CreateObject(ADODB.Command)    sWhere =    oConn.ConnectionString = STRCON
    oConn.Open
    设置oCmd.ActiveConnection = oConn    选择的情况下TIPO
        情况下的g
            sSQL =SELECT cve_gr,DESCR从遗传ORDER BY DESCR;
        案z的
            sSQL =SELECT cve_zn,DESCR FROM Zn,且cve_gr = ORDER BY DESCR;?
            如果IsArray的(PARAMS)然后
                设置OPAR = oCmd.CreateParameter(PARAMS(0),129,1,2,则params(1))
                oCmd.Parameters.Append(OPAR)
            万一
        其他情况下,
            getCatalogo = FALSE
            退出功能
    最终选择    oCmd.CommandText = sSQL
    ORS设置= oCmd.Execute()
    如果不oRs.EOF然后
        的Response.Write(JSONStringify(ORS))
        getCatalogo =真
    其他
        getCatalogo = FALSE
    万一
    oConn.Close
最终功能aVals(0)=cve_gr
aVals(1)=的Request.QueryString(GR)
如果不getCatalogo(的Request.QueryString(T),aVals)然后
    %GT;错误&LT;%
万一%GT;

JSON-字符串化-parser.asp

 &LT;! - #include文件=vbsTyper.asp - &GT;
&LT;脚本=服务器LANGUAGE =JScript的&GT;    功能JSONStringify(对象){
        VBSTypeName(对象);
        返回JSON.stringify(对象,stringifyData);
    }    功能stringifyData(架,钥匙,价值){
        VAR STYPE ='';
        VAR的结果;        //response.write('$p$p...holder='+支架+',关键='+键+',值='+值);
        STYPE = VBSTypeName(值);
        //response.write('post ='+ STYPE);        //response.write(sType);
        开关(S型){
            案词典:
                结果='{';
                对于(VAR ENR =新的枚举(值);!enr.atEnd(); enr.moveNext()){
                    键= enr.item();
                    结果+ ='+按键+':+ JSON.stringify(value.Item(键));
                };
                结果+ ='};
                返回(结果);
                打破;
            案记录:
                的Response.Write(在这里!');
                VAR STEMP ='';
                结果='{';
                而(!value.EOF){
                    如果(莱恩(结果)大于0){
                        结果+ ='';
                    }
                    结果+ ='{';
                    对于(VAR I = value.Fields.Count - 1; I&GT; = 0; I - ){
                        如果(LEN(STEMP)大于0){
                            STEMP + ='';
                        }
                        STEMP + ='+ value.Fields(I)。名称+':+ JSON.stringify(value.Fields(我)。价值);
                    };
                    结果+ ='};
                }
                结果+ ='};
                返回结果;
                打破;
            默认:
                //response.write(sType);
                返回(值);
        }
        //返回的值以让它以通常的方式进行处理
        返回结果;
   }&LT; / SCRIPT&GT;

vbsTyper.asp

 &LT;%
功能VBSTypeName(OBJ)
    暗淡STYPE
    STYPE = CSTR(类型名(OBJ))
    的Response.Write(STYPE)
    VBSTypeName = STYPE
结束功能
%GT;


解决方案

样实现呢......

短版:我不得不修改json2.asp和破解字符串化()函数的定义,使其作品

长的版本

后来见code的每一行和问题放弃。我决定去看看成<一个href=\"https://github.com/nagaozen/asp-xtreme-evolution/blob/master/lib/axe/classes/Parsers/json2.asp\"相对=nofollow> json2.asp (AXE框架),并尝试看看它那里发生。

看看我看到:

这行,如果自定义拉丝解析器发现,但后来没有做任何事情682 687那里有一个验证...只返回对象值。

有从这里猜测,因为我不了解以及如何工作的每一个Javascript实现,但言下之意的原来的code运行良好,一个非标准的JavaScript间preTER( 阅读一切,但微软在这里)将强制对象的序列化在这个sutuation,但JScript的跨preTER尝试解析对象和传递价值的无效。导致使用自定义stringyfier无法读取函数传递的对象,每一个功能。

我就是这样做解决好,我行688之前插入code的这个块,强制执行与作为参数避免隐式分析直接传递值自定义stringyfier。

  //哈克和放大器;修补正确交付对象的字符串化-ING
        // IDK如果这是正确的或不但是在VBScript工作
        如果(替代){
            VAR textval =代表(这一点,'',值);
            值= textval;
        }

后来我不得不做的 JSON-字符串化-parser.asp一些修改,因为我必须解决导致这一code一些错误

 &LT;! - #include文件=vbsTyper.asp - &GT;
&LT;脚本=服务器LANGUAGE =JScript的&GT;    功能JSONStringify(对象){
        // VBSTypeName(对象);
        返回JSON.stringify(对象,stringifyData,4);
    }    功能stringifyData(架,钥匙,价值){
        VAR STYPE ='';
        VAR的结果;        //response.write('$p$p...holder='+支架+',关键='+键+',值='+值);
        STYPE = VBSTypeName(值);
        //response.write('post ='+ STYPE);        //response.write(sType);
        开关(S型){
            案词典:
                结果='{';
                对于(VAR ENR =新的枚举(值);!enr.atEnd(); enr.moveNext()){
                    键= enr.item();
                    结果+ ='+按键+':+ JSON.stringify(value.Item(键));
                };
                结果+ ='};
                返回(结果);
                打破;
            案记录:
                //response.write('here !!!');
                VAR STEMP;
                结果='';
                而(!value.EOF){
                    如果(result.length大于0){
                        结果+ ='';
                    }
                    结果+ ='{';
                    STEMP =''
                    对于(VAR I = 0; I&LT; value.fields.Count;我++){
                        如果(sTemp.length大于0){
                            STEMP + ='';
                        }
                        //response.write(\"i=+ I +,);
                        STEMP + ='+ value.fields.item(I)。名称+':+ JSON.stringify(value.fields.item(我)。价值);
                    };
                    结果+ = STEMP +'};
                    value.moveNext();
                }
                结果={+结果+'};
                返回结果;
                打破;
            默认:
                //response.write(sType);
                返回(值);
        }
        //返回的值以让它以通常的方式进行处理
        返回结果;
   }&LT; / SCRIPT&GT;

解析部分记录的作品,来解析字典部分是相同的像<一所示href=\"http://stackoverflow.com/questions/5328858/json-stringify-fails-on-scripting-dictionary-objects\">JSON.Stringify对对象的Scripting.Dictionary (亦称我还没有测试过),但现在我有这个工作失败。

测试我有一个记录集对象业绩的变化在此输出

 {
    {\\釜\\:\\BC \\,\\descripcion \\:\\校准\\},
    {\\釜\\:\\CT \\,\\descripcion \\:\\中心\\},
    {\\釜\\:\\NE \\,\\descripcion \\:\\Norw \\},
    {\\釜\\:\\无\\,\\descripcion \\:\\诺尔\\},
    {\\釜\\:\\NT \\,\\descripcion \\:\\北\\},
    {\\釜\\:\\OC \\,\\descripcion \\:\\东\\},
    {\\釜\\:\\或\\,\\descripcion \\:\\西\\},
    {\\釜\\:\\PE \\,\\descripcion \\:\\笔\\},
    {\\釜\\:\\SE \\,\\descripcion \\:\\Southe \\},
    {\\釜\\:\\ZM \\,\\descripcion \\:\\大都会\\}
}

问题左

问题,我已经离开withis样的破解。


  • 这是确定的输出有()在beggining和字符
    结束,我一切都有逃生sencuences?或者它的东西
    这不应该发生。


  • 这种黑客是真的错了......我可以做的更好,在这
    样的情况?


  • 这件事情错在我的结论或论证??


i'm doing an application with ajax using jQuery and some other tools, and in some part i want to retrieve data with ajax using a classic ASP backend, i saw that exists a good implementation of a JSON class in AXE (Asp extreme edition) framework, and i used it but currently i don't understand how to use it well.

Edit: based on the correct answer of JSON.Stringify fails on Scripting.Dictionary objects Thread, i decided to make a custom function to process Recordsets.

Edit 2: Now i'm losing the value data when call JSON.stringify inside function JSONStringify(object).

when the Recordset is passed as value to JSONStringify everything is ok but when JSON.stringify is executed, the "value" parameter that must contain the recordset becomes undefined

What i'm expecting (example)

passing a Recordset with from a SQL query SELECT name, tel FROM users a see an output like this

[
    {"name":"Jonh Smith", "tel":"12345678"},
    {"name":"April Michelson", "tel":"77788802"},
    ...
]

passing a Dictionary and see something similar based in the elements declared in dictionary.

{
   "element1":"value1",
   "element2":"value2",
   "element3":"value3",
   "element4":"value4",
   "element5":"value5"
}

and if i like to support other type object i can do it expanding the function

Source Code

getcatalogos.asp

<!--#include file="../includes/conexion.asp" -->
<!--#include file="../includes/json2.asp" -->
<!--#include file="../includes/json-stringify-parser.asp" -->
<%
Response.ContentType = "application/json"
dim aVals(2)

function getCatalogo(tipo, params)
    Dim oConn,oCmd,sSQL,oRs,cont2
    Dim aData,oPar,cont
    dim Info 

    set oConn = Server.CreateObject("ADODB.Connection")
    set oCmd = Server.CreateObject("ADODB.Command")

    sWhere = ""

    oConn.ConnectionString = strcon
    oConn.Open
    Set oCmd.ActiveConnection = oConn

    select case tipo
        case "g"
            sSQL = " SELECT cve_gr, descr FROM gr ORDER BY descr ;"
        case "z" 
            sSQL = " SELECT cve_zn, descr FROM zn WHERE cve_gr = ? ORDER BY descr ;"
            if IsArray(params) Then
                Set oPar=oCmd.CreateParameter (params(0),129,1,2,params(1))
                oCmd.Parameters.Append(oPar)
            End if
        case else
            getCatalogo = false
            exit function
    end select

    oCmd.CommandText = sSQL
    Set oRs = oCmd.Execute()
    if Not oRs.EOF Then
        response.write(JSONStringify(oRs))
        getCatalogo = true
    else
        getCatalogo = false
    end if
    oConn.Close
end function

aVals(0) = "cve_gr"
aVals(1) = request.querystring("gr")
if Not getCatalogo(request.querystring("t"),aVals) Then
    %>error<%
end if

%>

json-stringify-parser.asp

<!--#include file="vbsTyper.asp" -->
<script runat="server" language="JScript">

    function JSONStringify(object) {
        VBSTypeName(object);
        return JSON.stringify(object,stringifyData);
    }

    function stringifyData(holder, key, value) {
        var sType = '';
        var result;

        //response.write('pre...holder=' + holder + ',key=' + key + ',value=' + value);
        sType = VBSTypeName(value);
        //response.write('post =' + sType);

        //response.write(sType);
        switch(sType){
            case 'Dictionary':
                result = '{';
                for(var enr = new Enumerator(value); !enr.atEnd(); enr.moveNext()){
                    key = enr.item();
                    result += '"' + key + '": ' + JSON.stringify(value.Item(key));
                };
                result += '}';
                return(result);
                break;
            case 'Recordset':
                response.write('here!!!');
                var sTemp = '';
                result = '{';
                while(!value.EOF){
                    if(Len(result) > 0){
                        result += ',';
                    }
                    result += '{';
                    for (var i = value.Fields.Count - 1; i >= 0; i--){
                        if(len(sTemp) > 0){
                            sTemp += ',';
                        }
                        sTemp += '"' + value.Fields(i).name + '":' + JSON.stringify( value.Fields(i).value);
                    };
                    result += '}';
                }   
                result += '}';
                return result;
                break;
            default:
                //response.write(sType);
                return(value);
        }     
        // return the value to let it be processed in the usual way
        return result;
   }

</script>

vbsTyper.asp

<%
Function VBSTypeName(Obj)
    dim sType 
    sType = Cstr(TypeName(Obj))
    response.write(sType)
    VBSTypeName = sType
End Function
%>

解决方案

kind of achieve it...

Short version: i had to modify the json2.asp and hack the stringify() function definition to make it works.

Long Version

later of see every line of code and giving up on the problem. i decided to take a look into json2.asp (AXE Framework) and try to see what it happening there.

look what i see:

from the lines 682 to 687 theres a validation if a custom stringy parser is found but later doesn't do anything ... only returns the Object value.

there's speculation from here, because i don't understand well how works every Javascript implementation, but implying that the original code runs well, that a standart javascript interpreter (read everything else but microsoft here) will force a serialization of the object in this sutuation, but the JScript interpreter try to parse the object and pass the value as null. resulting in that every function that uses a custom stringyfier can't read the object passed in the function.

what i did to resolve ok i inserted this chunk of code before line 688, forcing to execute the custom stringyfier with value directly passed as argument avoiding the implicit parsing.

        // Hack & patch to deliver the stringify-ing of the object correctly
        // IDK if this is CORRECT or dont but it works in VbScript
        if(replacer){
            var textval = rep(this,'',value);
            value = textval;
        }

later i had to do some changes in json-stringify-parser.asp because i had to fix some bugs resulting in this code

<!--#include file="vbsTyper.asp" -->
<script runat="server" language="JScript">

    function JSONStringify(object) {
        //VBSTypeName(object);
        return JSON.stringify(object,stringifyData,4);
    }

    function stringifyData(holder, key, value) {
        var sType = '';
        var result;

        //response.write('pre...holder=' + holder + ',key=' + key + ',value=' + value);
        sType = VBSTypeName(value);
        //response.write('post =' + sType);

        //response.write(sType);
        switch(sType){
            case 'Dictionary':
                result = '{';
                for(var enr = new Enumerator(value); !enr.atEnd(); enr.moveNext()){
                    key = enr.item();
                    result += '"' + key + '": ' + JSON.stringify(value.Item(key));
                };
                result += '}';
                return(result);
                break;
            case 'Recordset':
                //response.write('here!!!');
                var sTemp;
                result = '';
                while(!value.EOF){
                    if(result.length > 0){
                        result += ',';
                    }
                    result += '{';
                    sTemp=''
                    for (var i = 0; i < value.fields.Count; i++){
                        if(sTemp.length > 0){
                            sTemp += ',';
                        }
                        //response.write("i=" + i + ",");
                        sTemp += '"' + value.fields.item(i).name + '":' + JSON.stringify( value.fields.item(i).value);
                    };
                    result += sTemp + '}';
                    value.moveNext();
                }   
                result = '{' + result  + '}';
                return result;
                break;
            default:
                //response.write(sType);
                return(value);
        }     
        // return the value to let it be processed in the usual way
        return result;
   }

</script>

the part to parse a Recordset works, the part to parse a dictionary is same like the shown in JSON.Stringify fails on Scripting.Dictionary objects (a.k.a. i haven't tested yet) but for now i'm done with this.

testing my changes with a recordset object results in this output

"{
    {\"clave\":\"BC\",\"descripcion\":\"Cal\"},
    {\"clave\":\"CT\",\"descripcion\":\"Center\"},
    {\"clave\":\"NE\",\"descripcion\":\"Norw\"},
    {\"clave\":\"NO\",\"descripcion\":\"Nore\"},
    {\"clave\":\"NT\",\"descripcion\":\"North\"},
    {\"clave\":\"OC\",\"descripcion\":\"East\"},
    {\"clave\":\"OR\",\"descripcion\":\"West\"},
    {\"clave\":\"PE\",\"descripcion\":\"Pen\"},
    {\"clave\":\"SE\",\"descripcion\":\"Southe\"},
    {\"clave\":\"ZM\",\"descripcion\":\"Met\"}
}"

Questions Left

question that i have left withis kind of hack.

  • it's Ok that the output has (") character at the beggining and the end and i everything else has escape sencuences ?? or it's something that should not occurs.

  • this kind of hack is really wrong ... i can do it better, in this kind of situation ?

  • it's something wrong in my conclusion or arguments ??

这篇关于经典ASP:如何使用AXE JSON实现一个RecordSet转换成JSON符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆