Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a x-www-url-encoded string into a Map[String, String] using Lift?

Tags:

scala

lift

From Lift, I'm getting a string of the form

TOKEN=EC%2d454178600K772032D&TIMESTAMP=2011%2d06%2d29T13%3a10%3a58Z&CORRELATIONID=cbd56e97cad38&ACK=Success&VERSION=64&BUILD=1936884

from the response of an HTTP request.

Although it's probably ultra-trivial, I can't find the Lift function that parses this into a nice Map[String, String]. Any help?

like image 306
Jean-Philippe Pellet Avatar asked Jun 29 '11 13:06

Jean-Philippe Pellet


2 Answers

From Lift's Req.scala:

// calculate the query parameters
lazy val queryStringParam:  (List[String], Map[String, List[String]]) = {
  val params: List[(String, String)] =
    for {
      queryString <- request.queryString.toList
      nameVal <- queryString.split("&").toList.map(_.trim).filter(_.length > 0)
      (name, value) <- nameVal.split("=").toList match {
        case Nil => Empty
        case n :: v :: _ => Full((urlDecode(n), urlDecode(v)))
        case n :: _ => Full((urlDecode(n), ""))
      }} yield (name, value)

        val names: List[String] = params.map(_._1).distinct
  val nvp: Map[String, List[String]] = params.foldLeft(Map[String, List[String]]()) {
    case (map, (name, value)) => map + (name -> (map.getOrElse(name, Nil) ::: List(value)))
  }

  (names, nvp)
}
like image 63
David Pollak Avatar answered Sep 23 '22 18:09

David Pollak


I haven't seen any Lift's implementation for that. You can achieve this with something like this:

val input = "TOKEN=EC%2d454178600K772032D&TIMESTAMP=2011%2d06%2d29T13%3a10%3a58Z&CORRELATIONID=cbd56e97cad38&ACK=Success&VERSION=64&BUILD=1936884"
val res = input.split('&') map { str =>
    val pair = str.split('=')
    (pair(0) -> pair(1))
} toMap

note: it assumes, that you have a well-formed string. In your code you should probably check if the string is ok.

like image 31
George Avatar answered Sep 21 '22 18:09

George