2

我在 ASP Classic 中得到一个 JSON 结果,如下所示:

<script language="JScript" runat="server" src="json2.js"></script>
<%
Response.ContentType = "text/html"

Dim HttpReq
Dim Diamond
Set HttpReq = Server.CreateObject("Msxml2.ServerXMLHTTP.6.0")
HttpReq.open "GET", "http://url.com?id=" & Request.QueryString("id"), False
HttpReq.send

res = HttpReq.responseText
Set res = JSON.parse(res)
%>

有用。

假设 JSON 结果如下所示:

res = {
    gallery: { 
        image1: { img: 'source url', thumb: 'source url' },
        image2: { img: 'source url', thumb: 'source url' },
        image3: { img: 'source url', thumb: 'source url' }
    },
    another_param1: 'foo',
    another param2: 'bar',
    ...
}

然后我想迭代画廊对象,不是在 JScript 中,而是在 VBScript 中。

我怎样才能做到这一点?

非常感谢您提前。

4

3 回答 3

2

如果确实需要在 VBScript 中枚举对象的属性,则需要将对象转换为字典。这是一个简单的函数,它将接受一个 JScript 对象并返回Scripting.Dictionary

<script runat="server" language="javascript">

    function JScriptObjectToDictionary(o)
    {
        var dict = new ActiveXObject("Scripting.Dictionary")

        for (var prop in o)
        {
            if (o.hasOwnProperty(prop))
            {
                dict.add(prop, o[prop]);
            }
        }

        return dict;
    }
</script>

使用页面中存在的此函数,您现在可以将gallery属性转换为字典:

 res.gallery = JScriptObjectToDictionary(res.gallery)

然后您可以迭代为:

 For Each key in res.gallery
     Response.Write key & ": " & res.gallery(key).img & "<br />"
 Next

话虽如此,值得指出的是,像 image1、image2 这样命名为系列的属性是一个糟糕的选择。如果 JSON 将画廊定义为一个简单的数组而不是一个对象,那就更好了。如果您能够影响 JSON 设计,您应该要求对其进行更改。

于 2012-05-28T12:11:24.750 回答
1

AXE(ASP Xtreme Evolution) JSON 解析器将为您解决问题。只是谷歌它。在文件中包含 AX 后;

set Info = JSON.parse(RES)
Response.write(Info.gallery & vbNewline)
Response.write(Info.gallery.image & vbNewline)

编辑 - -

当您需要为画廊创建循环时;

dim key : 对于 Info.keys() Response.write( key & vbNewline ) 中的每个键

于 2012-05-28T10:57:50.763 回答
0

如果 JSON 很简单并且始终具有相同的结构,您可以自己解析它,它既快速又简单,不需要外部库。

res = "{"_
    &"gallery: { "_
    &"    image1: { img: 'source url1', thumb: 'source url1' },"_
    &"    image2: { img: 'source url2', thumb: 'source url2' },"_
    &"    image3: { img: 'source url3', thumb: 'source url3' }"_
    &"},"_
    &"another_param1: 'foo',"_
    &"another param2: 'bar'"_
    &"}"

'convert the JSON string to an array
Set oRegExpre = new RegExp
oRegExpre.Global = true
oRegExpre.Pattern = "{ img.*?}"

'iterate the array (records)
Set records = oRegExpre.Execute(res)
for each record in records
  aRecord = split(record,"'")
  key1 = replace(aRecord(0),"{ ","")
  key2 = replace(aRecord(2),", ","")
  wscript.echo key1 & aRecord(1) 'schow key & value pairs
  wscript.echo key2 & aRecord(3)
next

=>
img: source url1
thumb: source url1
img: source url2
thumb: source url2
img: source url3
thumb: source url3
于 2012-05-28T14:40:54.223 回答