Convert query string to map in scala

I have a query string in this form:

val query = "key1=val1&key2=val2&key3=val3

I want to create a map with the specified key / value pairs. So far I am doing it like this:

//creating an iterator with 2 values in each group. Each index consists of a key/value pair
val pairs = query.split("&|=").grouped(2)

//inserting the key/value pairs into a map
val map = pairs.map { case Array(k, v) => k -> v }.toMap

Is there a problem with this like me? If so, is there some kind of library that I could use for this?

+4
source share
1 answer

The following is an approach using URLEncodedUtils :

import java.net.URI

import org.apache.http.client.utils.URLEncodedUtils
import org.apache.http.{NameValuePair => ApacheNameValuePair}

import scala.collection.JavaConverters._
import scala.collection.immutable.Seq

object GetEncodingTest extends App {
  val url = "?one=1&two=2&three=3&three=3a"
  val params = URLEncodedUtils.parse(new URI(url), "UTF_8")

  val convertedParams: Seq[ApacheNameValuePair] = collection.immutable.Seq(params.asScala: _*)
  val scalaParams: Seq[(String, String)] = convertedParams.map(pair => pair.getName -> pair.getValue)
  val paramsMap: Map[String, String] = scalaParams.toMap
  paramsMap.foreach(println)
}
+2
source

Source: https://habr.com/ru/post/1672367/


All Articles