Technipelago AB

Technipelago Blog Stuff that we learned...


Parse query string with Groovy

Publicerad den 31 Jan 2012

This little piece of Groovy code transforms a URL query string into a Map

One day I needed to parse a URL query string outside of a web container using only Groovy. I was surprised there was no standard was to do this and I could not find a small convenient library to use. So I rolled my own.

This is what I came up with:

// Define a complex query to test with.
def url = new URL("http://www.google.com/" +
  "?sclient=psy-ab&hl=sv&site=&source=hp&" +
  "q=parse+query+string+groovy&pbx=1&" +
  "oq=parse+query+string+groovy&aq=f&aqi=&aql=&gs_sm=e&" +
  "gs_upl=2640l7169l0l7417l25l14l0l11l11l0l102l616l13.1l25l0&" +
  "bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=41e3a896b66de401&" +
  "biw=1368&bih=1010")

def map = url.query.split('&').inject([:]) {map, kv-> def (key, value) = kv.split('=').toList(); map[key] = value != null ? URLDecoder.decode(value) : null; map }

assert map.q == "parse query string groovy"

 

Works great! So let's add this method to the URL class

URL.metaClass.queryAsMap = {
  if(!delegate.query) return [:]

  delegate.query.split('&').inject([:]) {map, kv ->
    def (key, value) = kv.split('=').toList()
    if(value != null) {
      map[key] = URLDecoder.decode(value)
    }
    return map
  }
}

Tags: groovy


« Back