Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting keys from json string using json4s

Tags:

json

scala

json4s

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

like image 346
homar Avatar asked May 18 '26 20:05

homar


1 Answers

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

  • if the value's type is String just extract as String
  • if the value's type is others, use the json4s to parse it to as JSON string
  • finally extract the JValue as Map[String, String].
like image 100
chengpohi Avatar answered May 20 '26 10:05

chengpohi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!