Search code examples
jsonscalajson4s

Parsing JObject for key and values with json4s-jackson


How can I get the keys scenario0 and scenario1 for each JObject in my List?

poop is a:

poop: List[org.json4s.JsonAST.JValue] = List(JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))), JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))))

Code:

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

implicit val formats = DefaultFormats

val json = parse("""
         {
            "address0": {
              "scenario0": {
                "street": "Bulevard",
                "city": "Helsinki"
              },
              "scenario1": {
                "street": "Bulevard",
                "city": "Helsinki"
              }
            },
            "address1": {
              "scenario0": {
                 "street": "Bulevard",
                 "city": "Helsinki"
               },
               "scenario1": {
                 "street": "Bulevard",
                 "city": "Helsinki"
               }
            }
         }""")

val poop = (json \ "address0").children
poop.foreach(p => {

})

Solution

    1. If you need values and don't have fixed schema: val poop: Map[String, Any] = json.asInstanceOf[JObject].values returns Map(address0 -> Map(scenario0 -> Map(street -> Bulevard, city -> Helsinki), scenario1 -> Map(street -> Bulevard, city -> Helsinki)), address1 -> Map(scenario0 -> Map(street -> Bulevard, city -> Helsinki), scenario1 -> Map(street -> Bulevard, city -> Helsinki)))
    2. If you need values and have fixed schema then extracting of case class could be useful.
    3. If you need AST: val poop = json.asInstanceOf[JObject].obj gives List[org.json4s.JsonAST.JField] = List((address0,JObject(List((scenario0,JObject(List((street,JString(Bulevard)), (city,JString(Helsinki))))), (scenario1,JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))))))), (address1,JObject(List((scenario0,JObject(List((street,JString(Bulevard)), (city,JString(Helsinki))))), (scenario1,JObject(List((street,JString(Bulevard)), (city,JString(Helsinki)))))))))

    p.s. I omitted guardian checks for the sake of simplicity.