#pragma strict

/*  Import and export JSON to/from Unity
 *  by Mike Hergaarden "Leepo" - M2H.nl
 */

function Awake ()
{
	//Import JSON
	var jsonString = "{ \"serverName\" : \"jointA\" , \"center\" : \"3.0 4.0 5.0\" , \"diameter\" : \"22.0\" }";
	var jsonHash : Hashtable = eval(jsonString);
	for(var key : String  in jsonHash.Keys){
		Debug.Log("Key="+ key+" Value="+jsonHash[key]);
	}
   
	//Export JSON: Simple
	Debug.Log("JSON string 1 ="+CreateStringFromJSON(jsonHash));
	//Output =    JSON string 1 ={"objectName" : "jointA", "diameter" : "22.0", "center" : "3.0 4.0 5.0"}
   
	//Export JSON: Nested
	var myJSONObject : Hashtable = {"bindings": [
		{"sername": "Bla", "players": "newURI", "regex": "^http://.*"},
		{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
		{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
		]
	};
	
	Debug.Log("JSON string 2 ="+CreateStringFromJSON(myJSONObject));
	//Output = JSON string 2 ={"bindings" : [
	//  {"sername" : "Bla", "regex" : "^http://.*", "players" : "newURI"},
	//  {"ircEvent" : "PRIVMSG", "method" : "deleteURI", "regex" : "^delete.*"},
	//  {"ircEvent" : "PRIVMSG", "method" : "randomURI", "regex" : "^random.*"}
	//  ]}
} 

function CreateStringFromJSON(myJSONObject : Hashtable) : String {
	var outputString : String = "{";	
	var first : boolean = true;
	for (var key : String  in myJSONObject.Keys)
	{		
		if(!first){
			outputString +=", ";
		}
		first=false;	
		
		if( myJSONObject[key].GetType()+"" == "Boo.Lang.Hash[]" ){
			outputString += "\""+key+"\" : [";
			var hashArray : Hashtable[] = myJSONObject[key];
			var first2 : boolean = true;
			for(var aHashTable: Hashtable in hashArray){
				if(!first2){
					outputString +=",";
				}
				outputString += CreateStringFromJSON(aHashTable);
				first2 = false;
			}
			outputString += "]";
		}else{
			outputString +="\""+key+"\" : \""+myJSONObject[key]+"\"";
		}		
	}	
	outputString += "}";	
	return outputString;
}