JSON Encoder

I wrote this function that accepts a Squirrel table or array and creates a JSON string. If something like this already exists, please don’t tell me–I spent most of the day yesterday on it :-). Other comments or observations welcome! I supposed I should use a blob instead of a string, right?

//make a JSON string from an array, table, interger, or string //call without second and third arguments function makeJSON(obj, outputString = "", slotName = "") { //if slotName is passed in, the object is a //table slot and therefore has a name if(slotName != "") outputString += "\"" + slotName + "\": "; switch(typeof(obj)) { case "string": outputString += "\"" + obj + "\""; break; case "integer": outputString += obj; break; case "table": outputString += "{"; local j = 0; foreach(name, slot in obj){ if(j > 0) outputString += ", "; outputString = makeJSON(slot, outputString, name); j++; } outputString += "}"; break; case "array": outputString += "["; foreach(i, element in obj){ if(i > 0) outputString += ", " outputString = makeJSON(element, outputString); } outputString += "]"; break; } return outputString; }

Awesome that you got it working - but I should probably let you know:

If you want to emit JSON, you can set a squirrel table to your output port, then send it to an HTTP Request node. In the HTTP Request node, you can click the settings button (where you configure the URL you’ll be sending data to) and select “application/JSON” in the content type drop-down menu - you’ll then emit JSON :X

Thanks! Although I’m not sure whether that solves my issue. I was wanting to provide JSON in response to an HTTP request–such as if an iPhone app calls the imp to get the imp’s data–which is not possible at the moment anyway, I believe. When it becomes possible to request data from the imp, maybe the agent communications will take care of this for me?

Also, I just noticed some equivalent code in some of the documentation examples, which looks more robust than mine. Oh well. I do get a kick out of recursive routines.