Skip to content

Instantly share code, notes, and snippets.

@Mistat
Created October 21, 2016 10:30
Show Gist options
  • Save Mistat/c230f23c75f62c995ef34521c8c84804 to your computer and use it in GitHub Desktop.
Save Mistat/c230f23c75f62c995ef34521c8c84804 to your computer and use it in GitHub Desktop.
## https://forums.aws.amazon.com/message.jspa?messageID=675886
## convert HTML FORM POST data to JSON for insertion directly into a Lambda function
## get the raw post data from the AWS built-in variable and give it a nicer name
#set($rawPostData = $input.path('$'))
## first we get the number of "&" in the string, this tells us if there is more than one key value pair
#set($countAmpersands = $rawPostData.length() - $rawPostData.replace("&", "").length())
## if there are no "&" at all then we have only one key value pair.
## we append an ampersand to the string so that we can tokenise it the same way as multiple kv pairs.
## the "empty" kv pair to the right of the ampersand will be ignored anyway.
#if ($countAmpersands == 0)
#set($rawPostData = $rawPostData + "&")
#end
## now we tokenise using the ampersand(s)
#set($tokenisedAmpersand = $rawPostData.split("&"))
## we set up a variable to hold the valid key value pairs
#set($tokenisedEquals = [])
## now we set up a loop to find the valid key value pairs, which must contain only one "="
#foreach( $kvPair in $tokenisedAmpersand )
#set($countEquals = $kvPair.length() - $kvPair.replace("=", "").length())
#if ($countEquals == 1)
#set($kvTokenised = $kvPair.split("="))
#if ($kvTokenised[0].length() > 0)
## we found a valid key value pair. add it to the list.
#set($devNull = $tokenisedEquals.add($kvPair))
#end
#end
#end
## next we set up our loop inside the output structure "{" and "}"
{
#foreach( $kvPair in $tokenisedEquals )
## finally we output the JSON for this pair and append a comma if this isn't the last pair
#set($kvTokenised = $kvPair.split("="))
"$util.urlDecode($kvTokenised[0])" : #if(!$kvPair.endsWith("="))"$util.escapeJavaScript($util.urlDecode($kvTokenised[1]))"#{else}""#end#if( $foreach.hasNext ),#end
#end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment