JSON to XML Converter

Here's a little JSON to XML converter that I threw together:

	function typeOf(value) {    // from crockford
                var s = typeof value;
                if(s === 'object') {
                    if(value) {
                        if( value instanceof Array) {
                            s = 'array';
                        }
                    } else {
                        s = 'null';
                    }
                }
                return s;
            }

            function json2xml(obj) {

                var out = '';
                switch (typeOf(obj)) {
                    case 'array' :
                     	out +=  '<array>';
                     	for (var i=0; i<obj.length; i++) {
                     		out=out + "<item>" + json2xml(obj[i]) + "</item>";
                     	}
                     	out += "</array>";
                        break;

                    case 'object' :
                        out += '<obj>';
                        for (var i in obj) {
                          out=out + "<" + i + ">" + json2xml(obj[i]) + "</" + i + ">";
                        }
                        out+="</obj>";
                        break;

                    case 'string' :
                       out+="<![CDATA[" + obj + "]]>";
                 	   break;
                    default:
                       out += obj;
                       break;
                 }
                 return out;
            }

            var myJson = "[{a:1},{a:2},{b:'Rock the fig'}]";
            var obj = eval(myJson);
            alert(json2xml(obj));

One thought on “JSON to XML Converter

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s