Here’s a quick one for you today!
I am working with the Twilio API today and their Webhook posts data back to you in application/x-www-form-urlencoded format instead of JSON as most services do these days.
We are so used to using JSON data, especially with REST services, that it just seems natural to convert the data into JSON data so it would be easier to manage.
For Example, the webhook was posting this text to us
ApiVersion=2010-04-01&MessageStatus=sent&SmsSid=SM38b42ea7884cb448df6d9da298a18ad4&SmsStatus=sent&To=%2B13182307383&From=%2B16292303364&MessageSid=SM38b42ea7884cb448df6d9da298a18ad4&AccountSid=ACde044b84fc63491e61e99395bec2f7c5"
Most you you will probably recognize this as similar to what you see behind URLs sometimes. In fact, that is exactly what it is. When behind the URL it is called a Query string is starts with a ?. When Posted as the content/body of an HTML request the leading ? is not included and it is called Form Encoded
You could of course parse that string and extract the info you need from it. But I figured I might as well just make a generic method that will turn it into JSON and be done with it.
So I wrote this quick procedure, really a method in our wxHTTP abstract class we use in many of our REST classes, but you get the idea.
PROCEDURE GLOBAL FormDataToJSON(inFormData)
retJSON is JSON
FOR EACH STRING aParm OF inFormData SEPARATED BY "&"
{"retJSON." + URLDecode(ExtractString(aParm,1,"=")) } = URLDecode(ExtractString(aParm,2,"="))
END
RESULT retJSON
That is looping through the string and breaking it apart at every &, which is how the data is separated. Then it takes that string and breaks it apart at the =, using the first half as the name of the JSON element and the second half as the value. This is another example of how indirection helps us do things that would be much more difficult without it!
The first two lines of my web service are now quite simple.
intext is string = WebserviceParameter(paramBuffer)
inJSON is JSON = FormDataToJSON(intext)
The first line is the raw post content, which is the string value I showed above. And then the second calls our marvelous new function to convert it to JSON. Resulting in a JSON object that looks like this
{
"ApiVersion":"2010-04-01",
"MessageStatus":"sent",
"SmsSid":"SM38b42ea7884cb448df6d9da298a18ad4",
"SmsStatus":"sent",
"To":"+13182307383",
"From":"+16292303364",
"MessageSid":"SM38b42ea7884cb448df6d9da298a18ad4",
"AccountSid":"ACde044b84fc63491e61e99395bec2f7c5"
}
Allowing us to now reference the values in our code using standard . syntax of the JSON object, such as
Alert.MessageID = inJSON.MessageSid
As I said just a quick one for you today, but hopefully it will save you some time if you run into a need to work with form-encoded data from a web service.

Nice work! We did something similar but more complex… I like this a lot!!
LikeLike