Search code examples
adobe-illustratorextendscriptjsx

How to convert XML to JSON object in JSX?


How can I convert an XML file to a JSON object?


Solution

  • Here is the simple code for XML to JSON conversion.

    function xmlToJson(xml) {
        // Create the return object
        var obj = {};
        if (xml.nodeKind() == "element") {
            if (xml.attributes().length() > 0) {
                for (var j = 0; j < xml.attributes().length(); j++) {
                    var attributeName = xml.attributes()[j].name();
                    obj[attributeName] = String(xml.attributes()[j]);
                }
            }
        } else if (xml.nodeKind() == "text") {
            obj['text'] = xml.text();
        }
        if (xml.children()) {
            for (var i = 0; i < xml.children().length(); i++) {
                var item = xml.child(i);
                if (xml.children()[i].nodeKind() == "text") {
                    obj['text'] = xml.children()[i].toString();
                } else {
                    var nodeName = item.name();
                    if (typeof(obj[nodeName]) == "undefined") {
                        obj[nodeName] = xmlToJson(item);
                    } else {
                        if (typeof(obj[nodeName].push) == "undefined") {
                            var old = obj[nodeName];
                            obj[nodeName] = [];
                            obj[nodeName].push(old);
                        }
                        obj[nodeName].push(xmlToJson(item));
                    }
                }
            }
        }
        return obj;
    };