2

I have a JSON body in the following form:

val body = 
{
    "a": "hello",
    "b": "goodbye"
}

I want to extract the VALUE of "a" (so I want "hello") and store that in a val. I know I should use "parse" and "Extract" (eg. val parsedjson = parse(body).extract[String]) but I don't know how to use them to specifically extract the value of "a"

2

2 Answers 2

3

To use extract you need to create a class that matches the shape of the JSON that you are parsing. Here is an example using your input data:

val body ="""
{
  "a": "hello",
  "b": "goodbye"
}
"""

case class Body(a: String, b: String)

import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = DefaultFormats

val b = Extraction.extract[Body](parse(body))

println(b.a) // hello
Sign up to request clarification or add additional context in comments.

Comments

1

You'd have to use pattern matching/extractors:

val aOpt: List[String] = for {
  JObject(map) <- parse(body)
  JField("a", JString(value)) <- map
} yield value

alternatively use querying DSL

parse(body) \ "a" match {
  case JString(value) => Some(value)
  case _              => None
}

These are options as you have no guarantee that arbitrary JSON would contain field "a".

See documentation

extract would make sense if you were extracting whole JObject into a case class.

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.