How to build a Map of lists of map from type safe config in scala

This code should be able to give you what you are looking for.

It builds up lists and maps for your bespoke structure.

The final reduceLeft, is because your json starts with a list, someConfig: [ ], and so I've flattened that out. If you wanted you could probably have removed the [ ]'s, as they as probably not required to represent the data you have.

//These methods convert from Java lists/maps to Scala ones, so its easier to use
private def toMap(hashMap: AnyRef): Map[String, AnyRef] = hashMap.asInstanceOf[java.util.Map[String, AnyRef]].asScala.toMap
private def toList(list: AnyRef): List[AnyRef] = list.asInstanceOf[java.util.List[AnyRef]].asScala.toList

val someConfig: Map[String, List[Map[String, String]]] =
  config.getList("someConfig").unwrapped().map { someConfigItem =>
    toMap(someConfigItem) map {
      case (key, value) =>
        key -> toList(value).map {
          x => toMap(x).map { case (k, v) => k -> v.toString }
        }
    }
  }.reduceLeft(_ ++ _)

Tags:

Scala