4

What is the best way to parse json string into classic asp using a library?

Dim jsonString
jsonString = {"date":"4/28/2017","custType":"100","vehicle":"1"}

Would like to have

response.write("<li> date :" & json("date") & "</li>")
4
  • Possible duplicate of Using VBscript to access all values in JSON data Commented Apr 29, 2017 at 4:59
  • 1
    @JoelCoehoorn there are plenty of libraries for parsing JSON in Classic ASP. Commented Apr 29, 2017 at 5:02
  • @JoelCoehoorn There are still tons legacy projects using Classic ASP. Commented Apr 29, 2017 at 10:52
  • 2
    @JoelCoehoorn - also, you can use Jscript rather than VBScript as your server side language in Classic ASP. JScript offers native handling of JSON Commented Apr 29, 2017 at 13:55

5 Answers 5

5

Got it working:

Using https://github.com/rcdmk/aspJSON

Dim jsonString
jsonString = {"date":"4/28/2017","custType":"100","vehicle":"1"}

Dim jsonObj, outputObj
set jsonObj = new JSONobject
set outputObj = jsonObj.parse(jsonString)

response.write("<li> date :" & outputObj("date") & "</li>")
response.write("<li> custType :" & outputObj("custType") & "</li>")
response.write("<li> vehicle :" & outputObj("vehicle") & "</li>")

If you need to iterate through the single object use outputObj.pairs

Dim props, prop
props = outputObj.pairs
for each prop in props
    response.write prop.name & " : " & prop.value & "<br>"
next

as referenced https://github.com/rcdmk/aspJSON/issues/20

Sign up to request clarification or add additional context in comments.

1 Comment

It's a really good library is that one, glad you found a solution.
2

As a quick solution for simple json structure and escaped values, this simple function returns the key values by splitting the json string on double quotes chr(34):

function getKeyValue(JsonString,key)
    myarray=split(JsonString,key,-1,1)
    if ubound(myarray)>0 then
        myarray2=split(myarray(1),chr(34),-1,1)
        getKeyValue=myarray2(2)
    else
        getKeyValue=""
    end if
end function

usage:

response.write("<li> date :" & getKeyValue(Your_Json_String_Here,"date") & "</li>")

Comments

1

Almost certain no-one will ever need this answer, but just in case.

Rather than rely on external libraries, or ScriptControlobjects, simply do it with some Server-Side JavaScript.

Set jsreader = New JsonReader
jsreader.loadJson(myJson)

adviser_id = jsreader.getElement("someField")

Using this VBScript module:

<%

class JsonReader

    private root

    private sub Class_Terminate()
        set root = nothing
    end sub

    public sub loadJson(sJson)
        set root = new_JsonEngine(sJson)
        if root.hasError() then err.Raise 10000, "JsonReader:loadJson", "Syntax Error"
    end sub

    public function getElement(sPath)
        getElement = root.getElement(sPath)
    end function

    public function getChildNodes(sPath)
        getChildNodes = split(root.getChildNodes(sPath), ",")
    end function

    public function elementExists(sElement)
        elementExists = root.elementExists(sElement)
    end function

end class

%>

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

function new_JsonEngine(sJson) {
    return new JsonEngine(sJson);
};

function JsonEngine(sJson) {
    var me = this;
    this.data = {};
    this.error = false;
    this.initialize = function(sJson) {
        try {
            this.data = JSON.parse(sJson);
        } catch (e) {
            me.error = true;
        }
    };

    this.elementExists = function (sElement) {
        var currentRoot = me.data;
        var aPath = sElement.split('.');
        var bExists  = true;
        for (var i = 0, len = aPath.length; i < len; i++) {
            currentRoot = currentRoot[aPath[i]];
            if (typeof currentRoot === "undefined") {
                bExists = false;
                break;
            }
        }

        return bExists;
    };

    this.getElement = function(sPath) {
        var node = me.data;
        var aPath = sPath.split('.');
        for(var i = 0, len = aPath.length; i < len; i++) {
            node = node[aPath[i]];
        }
        return (typeof node == "object" && node.length)? "[object Array]" : node;
    };
    this.getChildNodes = function(sPath) {
        var keys = [];
        var parentNode = me.data;
        if( sPath.length > 0 ) {
            var aPath = sPath.split('.');
            for(var i = 0, len = aPath.length; i < len; i++) {
                parentNode = parentNode[aPath[i]];
            }
        }
        for(var key in parentNode) {
            (sPath.length > 0)? keys.push(sPath + "." + key) : keys.push(key);
        }
        return keys;
    };
    this.hasError = function() {
        return me.error;
    };
    this.initialize(sJson);
}
</script>

Comments

0

' >>> A hundred times faster!

public function GetJsonObject( str_json )
    dim obj_script: Set obj_script = CreateObject("ScriptControl")
    obj_script.Language = "JScript"
    obj_script.Eval("var obj_json = " & str_json)
    set GetJsonObject = obj_script.Eval("obj_json")
end function

dim str_json: str_json = "{ date :'4/28/2017', custType: 100, vehicle: 1 }"
dim obj_json: set obj_json = GetJsonObject(str_json)

response.write("date :" & obj_json.date & "<br />")
response.write("custType :" & obj_json.custType & "<br />")
response.write("vehicle :" & obj_json.vehicle & "<br />")

' >>> no lib to include and when the JSON is very long, it works super fast also, not with lib "aspJSON". Plus fields can be read directly, no string like xxx("vehicle")

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
CreateObject("ScriptControl") gives ActiveX component can't create object: 'ScriptControl', so there are more steps required in order to use your solution.
0

Honestly, for every reader as of today, the Chilkat Tools component is just excellent at this task, reliable and fast, as it is compiled as a COM+ component. I'm using it since 2016 without a glitch for all my works related to JSON and Classic ASP.

I'm using it on my own servers, as being specialized in Classic ASP hosting.
So if your hosting company offers it, go for this component ! It will greatly simplify things

Otherwise, yes the `aspJSON` class may be enough for simple JSON data structures (I used it in the past).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.