任何用于在经典 ASP 中解析 JSON 的好库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1019223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:16:54  来源:igfitidea点击:

Any good libraries for parsing JSON in Classic ASP?

jsonasp-classicvbscript

提问by Mark Biek

I've been able to find a zillion libraries for generatingJSON in Classic ASP (VBScript) but I haven't been to find ANY for parsing.

我已经能够找到无数的库来在 Classic ASP (VBScript) 中生成JSON,但我还没有找到任何用于解析.

I want something that I can pass a JSON string and get back a VBScript object of some sort (Array, Scripting.Dictionary, etc)

我想要一些可以传递 JSON 字符串并取回某种 VBScript 对象的东西(数组、Scripting.Dictionary 等)

Can anyone recommend a library for parsing JSON in Classic ASP?

谁能推荐一个用于在经典 ASP 中解析 JSON 的库?

回答by Chris Nielsen

Keep in mind that Classic ASP includes JScript as well as VBScript. Interestingly, you can parse JSON using JScript and use the resulting objects directly in VBScript.

请记住,经典 ASP 包括 JScript 和 VBScript。有趣的是,您可以使用 JScript 解析 JSON,并直接在 VBScript 中使用生成的对象。

Therefore, it is possible to use the canonical https://github.com/douglascrockford/JSON-js/blob/master/json2.jsin server-side code with zero modifications.

因此,可以在零修改的服务器端代码中使用规范的https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Of course, if your JSON includes any arrays, these will remain JScript arrays when parsing is complete. You can access the contents of the JScript array from VBScript using dot notation.

当然,如果您的 JSON 包含任何数组,则解析完成后这些数组仍将是 JScript 数组。您可以使用点表示法从 VBScript 访问 JScript 数组的内容。

<%@Language="VBScript" %>
<%
Option Explicit
%>

<script language="JScript" runat="server" src='path/to/json2.js'></script>

<%

Dim myJSON
myJSON = Request.Form("myJSON") // "[ 1, 2, 3 ]"
Set myJSON = JSON.parse(myJSON) // [1,2,3]
Response.Write(myJSON)          // 1,2,3
Response.Write(myJSON.[0])      // 1
Response.Write(myJSON.[1])      // 2
Response.Write(myJSON.[2])      // 3
%>

回答by Shoban

Not sure about it. Have you checked ASP extremeframework which has JSON support?

不确定。您是否检查过支持 JSON 的ASP 极限框架?

回答by seanyboy

I couldn't get the extreme-evolution or Chris Nielson's suggestion to work. But, the following did work for me:

我无法让极端进化或 Chris Nielson 的建议起作用。但是,以下对我有用:

http://tforster.wik.is/ASP_Classic_Practices_For_The_21st_Century/JSON4ASP

http://tforster.wik.is/ASP_Classic_Practices_For_The_21st_Century/JSON4ASP

Download the following as "json2.min.asp"

将以下内容下载为“json2.min.asp”

http://tforster.wik.is/@api/deki/files/2/=json2.min.asp

http://tforster.wik.is/@api/deki/files/2/=json2.min.asp

Add the following line to the top of your ASP file:

将以下行添加到 ASP 文件的顶部:

<script language="javascript" runat="server" src="json2.min.asp"></script>

You can then use JSON in ASP.

然后您可以在 ASP 中使用 JSON。

   Dim car: Set car = JSON.parse("{""brand"":""subaru"",""model"":""outback sport"",""year"":2003," & _
                                 """colour"":""green"",""accessories"":[" & _
                                 "{""foglamps"":true},{""abs"":true},{""heatedSeats"":true}]}")

   Response.Write("brand: " & car.brand & "<br/>")                               
   Response.Write("model: " & car.model & "<br/>")                               
   Response.Write("colour: " & car.colour & "<br/>")                               
   Response.Write("has foglamps: " & CStr(car.accessories.get(0).foglamps) & "<br/>")                               

   car.accessories.get(0).foglamps = false
   Response.Write("has foglamps: " & CStr(car.accessories.get(0).foglamps) & "<br/>")                               
   Response.Write("new Json: " & JSON.stringify(car) & "<br/>")

   Set car = Nothing

Note: To parse through an array of items, you need to do the following:

注意:要解析一组项目,您需要执行以下操作:

   for each iTmp in testing
       if (TypeName(iTmp))<>"JScriptTypeInfo" then 
           Response.Write("Item: " &  iTmp & "<br/>")
       end if
   next

回答by Demon

I have recently implemented a VbsJsonclass, which has a "Decode" method to parse JSON to VBScript and a "Encode" method to generate JSON from VBScript. The code is somewhat long, so I don't paste it here.

我最近实现了一个VbsJson类,它有一个“解码”方法来解析 JSON 到 VBScript,还有一个“编码”方法从 VBScript 生成 JSON。代码有点长,这里就不贴了。

回答by Stephen Quan

I wrote this answer when I was looking for a light-weight pure VBScript only solution.

我在寻找轻量级纯 VBScript 解决方案时写了这个答案。

By putting together a rudimentary JSON to XML converter, we can walk the JSON string and turn it into a Microsoft.XMLDOM document.

通过将基本的 JSON 到 XML 转换器放在一起,我们可以遍历 JSON 字符串并将其转换为 Microsoft.XMLDOM 文档。

From there, we use Microsoft's XML API including XPath queries to pluck out any values we wanted.

从那里,我们使用 Microsoft 的 XML API 包括 XPath 查询来提取我们想要的任何值。

This handles simple JSON, but, I never intended this answer for anything more sophisticated.

这处理简单的 JSON,但是,我从来没有打算将这个答案用于更复杂的事情。

For a more robust solution, the best JSON interpreter, is a proper Javascript engine. Therefore, I highly recommend the accepted answer to this question i.e. Any good libraries for parsing JSON in Classic ASP?

对于更强大的解决方案,最好的 JSON 解释器是合适的 Javascript 引擎。因此,我强烈推荐这个问题的公认答案,即任何用于在经典 ASP 中解析 JSON 的好库?

Function JSONtoXML(jsonText)
  Dim idx, max, ch, mode, xmldom, xmlelem, xmlchild, name, value

  Set xmldom = CreateObject("Microsoft.XMLDOM")
  xmldom.loadXML "<xml/>"
  Set xmlelem = xmldom.documentElement

  max = Len(jsonText)
  mode = 0
  name = ""
  value = ""
  While idx < max
    idx = idx + 1
    ch = Mid(jsonText, idx, 1)
    Select Case mode
    Case 0 ' Wait for Tag Root
      Select Case ch
      Case "{"
        mode = 1
      End Select
    Case 1 ' Wait for Attribute/Tag Name
      Select Case ch
      Case """"
        name = ""
        mode = 2
      Case "{"
        Set xmlchild = xmldom.createElement("tag")
        xmlelem.appendChild xmlchild
        xmlelem.appendchild xmldom.createTextNode(vbCrLf)
        xmlelem.insertBefore xmldom.createTextNode(vbCrLf), xmlchild
        Set xmlelem = xmlchild
      Case "["
        Set xmlchild = xmldom.createElement("tag")
        xmlelem.appendChild xmlchild
        xmlelem.appendchild xmldom.createTextNode(vbCrLf)
        xmlelem.insertBefore xmldom.createTextNode(vbCrLf), xmlchild
        Set xmlelem = xmlchild
      Case "}"
        Set xmlelem = xmlelem.parentNode
      Case "]"
        Set xmlelem = xmlelem.parentNode
      End Select
    Case 2 ' Get Attribute/Tag Name
      Select Case ch
      Case """"
        mode = 3
      Case Else
        name = name + ch
      End Select
    Case 3 ' Wait for colon
      Select Case ch
      Case ":"
        mode = 4
      End Select
    Case 4 ' Wait for Attribute value or Tag contents
      Select Case ch
      Case "["
        Set xmlchild = xmldom.createElement(name)
        xmlelem.appendChild xmlchild
        xmlelem.appendchild xmldom.createTextNode(vbCrLf)
        xmlelem.insertBefore xmldom.createTextNode(vbCrLf), xmlchild
        Set xmlelem = xmlchild
        name = ""
        mode = 1
      Case "{"
        Set xmlchild = xmldom.createElement(name)
        xmlelem.appendChild xmlchild
        xmlelem.appendchild xmldom.createTextNode(vbCrLf)
        xmlelem.insertBefore xmldom.createTextNode(vbCrLf), xmlchild
        Set xmlelem = xmlchild
        name = ""
        mode = 1
      Case """"
        value = ""
        mode = 5
      Case " "
      Case Chr(9)
      Case Chr(10)
      Case Chr(13)
      Case Else
        value = ch
        mode = 7
      End Select
    Case 5
      Select Case ch
      Case """"
        xmlelem.setAttribute name, value
        mode = 1
      Case "\"
        mode = 6
      Case Else
        value = value + ch
      End Select
    Case 6
      value = value + ch
      mode = 5
    Case 7
      If Instr("}], " & Chr(9) & vbCr & vbLf, ch) = 0 Then
        value = value + ch
      Else
        xmlelem.setAttribute name, value
        mode = 1
        Select Case ch
        Case "}"
          Set xmlelem = xmlelem.parentNode
        Case "]"
          Set xmlelem = xmlelem.parentNode
        End Select
      End If
    End Select
  Wend

  Set JSONtoXML = xmlDom
End Function

The above script, transforms the following JSON:

上面的脚本转换了以下 JSON:

{
  "owningSystemUrl": "http://www.arcgis.com",
  "authInfo": {
    "tokenServicesUrl": "https://www.arcgis.com/sharing/rest/generateToken",
    "isTokenBasedSecurity": true
  }
}

into:

进入:

<xml owningSystemUrl="http://www.arcgis.com">
    <authInfo
        tokenServicesUrl="https://www.arcgis.com/sharing/rest/generateToken"
        isTokenBasedSecurity="true" >
    </authInfo>
</xml>

We can now use XPath to extract the tokenServicesUrl, for example:

我们现在可以使用 XPath 来提取tokenServicesUrl,例如:

dom.SelectSingleNode("xml/authInfo").getAttribute("tokenServicesUrl")
' Returns: "https://www.arcgis.com/sharing/rest/generateToken"

回答by peter

the solutions here are very good but sometimes overkill. If the JSON is simple and always the same structure you can parse it yourself, it's fast and simple.

这里的解决方案非常好,但有时会矫枉过正。如果 JSON 很简单,并且结构始终相同,您可以自己解析它,那么它既快速又简单。

 'read data from client
 records = Request.Form("records")
 'convert the JSON string to an array
 Set oRegExpre = new RegExp
 oRegExpre.Global = true
 oRegExpre.Pattern = "[\[\]\{\}""]+"
 records = replace(records, "},{","||")
 records = oRegExpre.Replace(records, "" )
 aRecords = split(records,"||")
 'iterate the array and do some cleanup
 for each rec in aRecords
   aRecord = split(rec,",")
   id          = split(aRecord(1),":")(1)
   field       = split(aRecord(0),":")(0)
   updateValue = split(aRecord(0),":")(1)
   updateValue = replace(updateValue,chr(10),"\n")
   updateValue = replace(updateValue,chr(13),"\r")
   updateValue = replace(updateValue,"'","''")
  'etc
next

回答by Joe Niland

AXE is a great library but is rather heavy if you just need JSON processing functionality.

AX 是一个很棒的库,但如果您只需要 JSON 处理功能,它就相当笨重。

I did, however, grab the base.asp file and the json.asp class file from the AXE project and successfully used them to implement JSON parsing in my project.

但是,我确实从 AX 项目中获取了 base.asp 文件和 json.asp 类文件,并成功地使用它们在我的项目中实现了 JSON 解析。

For JSON generation, I found aspjsonwas simpler to integrate. It also has more powerful json-related features. The axe documentation a little lacking and was more work to integrate into the project, however it does do a fine job of serializing its JSON VB object back to a string.

对于 JSON 生成,我发现aspjson更易于集成。它还具有更强大的 json 相关功能。ax 文档有点缺乏并且需要更多的工作来集成到项目中,但是它在将其 JSON VB 对象序列化回字符串方面做得很好。