can someone tell me how to extract keys from json using json4s. My use case: json stored as string in scala variable:
{
"key1" : "val1",
"key2" : ["12", "32"],
"key3" : {"keyN" : "valN"}
}
I'd like to transform this into a following Map[String, String]:
(key1 -> "val1", key2 -> "[\"12\",\"32\"]", key3 -> "{\"keyN\":\"valN\"}"
is there a simple way to achieve this with json4s? Thanks in advance
val result: Map[String, String] = parse( """ {
| "key1" : "val1",
| "key2" : ["12", "32"],
| "key3" : {"keyN" : "valN"}
| }""".stripMargin).mapField(k => {
val v: String = k._2 match {
case s: JString => k._2.extract[String]
case _ => write(k._2)
}
(k._1, JString(v))
}).extract[Map[String, String]]
println(result)
You can use mapField map the JValue toString
String just extract as Stringjson4s to parse it to as JSON stringJValue as Map[String, String].If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With