3

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

2 Answers 2

4
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].
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, works fine. I didn't see mapField method which is a key here :(
0
implicit val formats = DefaultFormats

val a = parse(""" { "numbers" : [1, 2, 3, 4] } """)
println(a.extract[Map[String, Any]].keySet)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.