Programing

클래식 ASP에서 JSON을 구문 분석하는 데 좋은 라이브러리가 있습니까?

lottogame 2020. 10. 27. 07:45
반응형

클래식 ASP에서 JSON을 구문 분석하는 데 좋은 라이브러리가 있습니까?


클래식 ASP (VBScript)에서 JSON 생성 하기위한 수많은 라이브러리를 찾을 수 있었지만 구문 분석 을 위해 아무것도 찾지 못했습니다 .

JSON 문자열을 전달하고 일종의 VBScript 개체 (Array, Scripting.Dictionary 등)를 반환 할 수있는 것을 원합니다.

누구나 Classic ASP에서 JSON 구문 분석을위한 라이브러리를 추천 할 수 있습니까?


Classic ASP에는 VBScript와 JScript가 포함되어 있습니다. 흥미롭게도 JScript를 사용하여 JSON을 구문 분석하고 결과 개체를 VBScript에서 직접 사용할 수 있습니다.

따라서 수정 사항없이 서버 측 코드에서 정식 https://github.com/douglascrockford/JSON-js/blob/master/json2.js 를 사용할 수 있습니다 .

물론 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
%>

그것에 대해 잘 모르겠습니다. JSON을 지원하는 ASP 익스트림 프레임 워크 를 확인 했습니까 ?


나는 극단적 인 진화 나 크리스 닐슨의 제안을 받아 들일 수 없었다. 그러나 다음은 저에게 효과적이었습니다.

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

다음을 "json2.min.asp"로 다운로드하십시오.

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

ASP 파일 맨 위에 다음 줄을 추가합니다.

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

그런 다음 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

참고 : 항목 배열을 구문 분석하려면 다음을 수행해야합니다.

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

최근에 VbsJson 클래스를 구현했습니다 .이 클래스에는 JSON을 VBScript로 구문 분석 하는 " Decode "메서드와 VBScript에서 JSON을 생성 하는 " Encode "메서드가 있습니다. 코드가 다소 길기 때문에 여기에 붙여 넣지 않습니다.


http://github.com/nagaozen/asp-xtreme-evolution/


가볍고 순수한 VBScript 전용 솔루션을 찾고있을 때이 답변을 썼습니다.

기초적인 JSON to XML 변환기를 결합하여 JSON 문자열을 살펴보고이를 Microsoft.XMLDOM 문서로 변환 할 수 있습니다.

여기에서 XPath 쿼리를 포함하는 Microsoft의 XML API를 사용하여 원하는 값을 추출합니다.

이것은 간단한 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?

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:

{
  "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:

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

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

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.

For JSON generation, I found aspjson was 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.


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.

 '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

참고URL : https://stackoverflow.com/questions/1019223/any-good-libraries-for-parsing-json-in-classic-asp

반응형