77

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

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

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

Community
  • 1
  • 1
Mark Biek
  • 135,050
  • 52
  • 150
  • 195
  • 1
    Why not create a DLL using the .net libraries available? – Shoban Jun 19 '09 at 17:58
  • 1
    Due to client limitations, I can't install anything on the server. I'm hoping for something that's pure Classic ASP. – Mark Biek Jun 19 '09 at 17:59
  • 1
    Really, I'd be happy to find something that just did arrays (including multi-dimensional). It wouldn't have to support the complete JSON spec. – Mark Biek Jun 19 '09 at 18:27
  • 3
    I know this is old but you can check my AspJson class. It does help me a lot: https://github.com/rcdmk/aspJSON – Ricardo Souza Jul 22 '15 at 16:18

8 Answers8

92

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.

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

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.

<%@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
%>
Cheeso
  • 180,104
  • 92
  • 446
  • 681
Chris Nielsen
  • 13,966
  • 5
  • 45
  • 54
  • 5
    The AXE library has this implemented [here](https://github.com/nagaozen/asp-xtreme-evolution/blob/master/lib/axe/classes/Parsers/json2.asp). – sholsinger Mar 08 '11 at 16:42
  • in fact this is a better solution that use the whole framework – Rafael Dec 16 '11 at 16:53
  • 6
    In case this doesn't work for anyone - I had to use `` instead of ` – Flash Jun 22 '12 at 04:10
  • 1
    @Andrew but doesn't that require changing the entire page to JScript instead of VBScript? I tried what you suggested and I get a VBScript compilation error when encountering `/*`. – Keith Aug 03 '15 at 15:39
  • 3
    Thanks for showing how to access the array elements. I spent a couple of hours fighting to figure it and gave up! – Santosh Dec 21 '16 at 14:27
  • Chris Nielsen How can I access the Object value? – sandipchandanshive Dec 15 '20 at 17:22
16

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

Shoban
  • 22,724
  • 8
  • 60
  • 105
  • You're my hero. That works perfectly! I'm going to take a look at the framework because it seems very handy but I was able to just lift out the JSON class and start using it by itself. – Mark Biek Jun 19 '09 at 18:33
  • wow.. Glad that I was able to help you ;-) – Shoban Jun 19 '09 at 18:36
  • 2
    I should mention though, that this JSON class seems to have trouble with Unicode. – Mark Biek Dec 22 '09 at 16:34
  • Just a tip for those trying to include the json2.asp file in a vbscript page via make sure you remove the tags from json2.asp Whilst experimenting with includes (our include code is v.complex) it got me scratching my head for a while. So hope it helps someone. :-) – Alex KeySmith Sep 16 '11 at 18:17
14

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

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

Download the following as "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:

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

You can then use JSON in ASP.

   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
seanyboy
  • 5,465
  • 7
  • 40
  • 56
  • 1
    You don't need a special ASP-flavored version of JSON2.js . Just use the original, and reference it using the `src` attribute of a ` – Cheeso Mar 09 '12 at 08:01
8

I have recently implemented a VbsJson class, 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.

Demon
  • 206
  • 2
  • 2
  • I converted the vbs files to asp. It works beautifully! Clean and simple. Many thanks Demon. – Mark Jan 31 '13 at 02:17
  • This is the only solution I could get to work using IIS / IIS Express 8.5. I suspect there have been significant changes to the ASP compilers that have rendered many of the other answers obsolete. – Keith Aug 03 '15 at 15:57
4

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

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

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

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

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"
Stephen Quan
  • 15,118
  • 3
  • 69
  • 63
3

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

  • 2
    The best one according to the comments of the library itself is here: https://github.com/nagaozen/asp-xtreme-evolution/blob/master/lib/axe/classes/Parsers/json2.asp You get an upvote. – sholsinger Mar 07 '11 at 23:06
2

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.

Joe Niland
  • 845
  • 14
  • 29
1

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
peter
  • 40,314
  • 5
  • 58
  • 99
  • I was trying to find a JSON library, when your post sent me away from my non-KISS approach. I realized I was going to really need to parse a message with a very well-defined format. I could slice and split it into something usable myself. Thanks. – alphadogg Sep 16 '12 at 21:25