Search code examples
jsonxmlasp-classic

XML String to JSON output


I have an XML response by querying an API

Set httpRequest = Server.CreateObject("MSXML2.ServerXMLHTTP")
httpRequest.Open "GET", url&"net/WebService.aspx?Login="&email&"&EncryptedPassword="&apikey&"&EDI_Name=Generic\"&filename, False
httpRequest.SetRequestHeader "Content-Type", "text/xml"
httpRequest.Send

using these codes.

This httpRequest brings me a XML string just like below :

<?xml version="1.0" encoding="UTF-8"?>
<xmldata>
    <Table>
        <ProductID>37883</ProductID>
        <ProductCode>G-49211</ProductCode>
        <ProductName>Preludes &amp; Postludes for the year beginning 9-11-2001/Ferr�</ProductName>
        <StockStatus>2</StockStatus>
        <LastModified>2014-02-27T09:50:00-08:00</LastModified>
        <LastModBy>1</LastModBy>
        <ProductPopularity>110</ProductPopularity>
    </Table>
    <Table>
        <ProductID>56236</ProductID>
        <ProductCode>BIS-SACD-1701-02</ProductCode>
        <ProductName>Bach: B minor Mass / Suzuki - Bach Collegium Japan (2 CDs)</ProductName>
        <StockStatus>1</StockStatus>
        <LastModified>2015-02-23T13:25:00-08:00</LastModified>
        <LastModBy>1</LastModBy>
    </Table>
</xmldata>

How can I Convert this xml string into a JSON response


Solution

  • You convert XML to JSON pretty easily using Chilkat's XML component.

    Once the XML is loaded, just recursively step through the tree and build the JSON object.

    function parseNode(node,indent){
        var rtn={};
        var attrCnt = node.NumAttributes;
        var chldCnt = node.NumChildren;
        if( attrCnt != 0 || chldCnt != 0){ rtn[node.Tag]={};}
        if(attrCnt > 0){
            for(var i = 0; i <= attrCnt- 1; i++){
                rtn[node.Tag]["@" + node.GetAttributeName(i)] = node.GetAttributeValue(i);
            }
            if(chldCnt == 0){ rtn[node.Tag]["#value"] = node.Content;}
        }
        if(chldCnt > 0){
            var ctArr = {};
            for(var i = 0; i <= chldCnt - 1; i++){
                var cTag = node.GetChildTagByIndex(i);
                var numWithTag = node.NumChildrenHavingTag(cTag);
                ctArr[cTag] = numWithTag;
            }
            for(var c in ctArr){
                if(ctArr[c]==1){
                    var nextNode = parseNode(node.GetNthChildWithTag(c,0),indent + "\t");
                    rtn[node.Tag][c] = nextNode[c];
                }else{
                    rtn[node.Tag][c] = [];
                    for(var ci = 0;ci <= ctArr[c] - 1;ci++){
                        var nextNode = parseNode(node.GetNthChildWithTag(c,ci),indent + "\t");
                        rtn[node.Tag][c][ci] = nextNode[c];
                    }
                }
            }
        }
        if(attrCnt == 0 && chldCnt == 0){ rtn[node.Tag] = node.Content;}
        return rtn;
    }
    
    var json={};
    var xml = new ActiveXObject("Chilkat_9_5_0.Xml");
    var success = xml.LoadXml(xmlStr);
    if(success){
        json=parseNode(xml,"");
    }
    

    ...and if you need this in a JSON string...

    function stringify(obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);
        } else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                v = obj[n];
                t = typeof(v);
                if (obj.hasOwnProperty(n)) {
                    if (t == "string") {
                        v = '"' + v + '"';
                    } else if (t == "object" && v !== null){
                        v = stringify(v);
                    }
                    json.push((arr ? "" : '"' + n + '":') + String(v));
                }
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    }