How to iterate org.json4s.JsonAST.JValue which is an array of JSON objects to separately work on each object in Scala?
Asked Answered
B

2

8

I have a sample array:

[{
    "abc":"1",
    "de":"1"
},
{
    "fgh":"2",
    "ij":"4"
}]

which is a org.json4s.JsonAST.JValue.

How is it possible to iterate over each object inside the array, to operate on each object separately?

Boxthorn answered 20/1, 2016 at 11:36 Comment(0)
M
18

The following is your json.

scala> json
res2: org.json4s.JValue = JArray(List(JObject(List((abc,JString(1)), (de,JString(1)))),
        JObject(List((fgh,JString(2)), (ij,JString(4))))))

There are several ways.

  1. use for syntax

    for {
      JArray(objList) <- json
      JObject(obj) <- objList
    } {
      // do something
      val kvList = for ((key, JString(value)) <- obj) yield (key, value)
      println("obj : " + kvList.mkString(","))
    }
    
  2. convert to scala.collection object

    val list = json.values.asInstanceOf[List[Map[String, String]]]
    //=> list: List[Map[String,String]] = List(Map(abc -> 1, de -> 1), Map(fgh -> 2, ij -> 4))
    

    or

    implicit val formats = DefaultFormats
    val list = json.extract[List[Map[String,String]]]
    //=> list: List[Map[String,String]] = List(Map(abc -> 1, de -> 1), Map(fgh -> 2, ij -> 4))
    

    and do something.

    for (obj <- list) println("obj : " + obj.toList.mkString(","))
    

Both outputs are

obj : (abc,1),(de,1)
obj : (fgh,2),(ij,4)

The document of json4s is here.

Menides answered 21/1, 2016 at 4:4 Comment(1)
Could you help to explain how this pattern matching works? t.filter( a => { a match { case JArray(b) => println(b) ; case other => println(other) } ; true }) . It returns 7 matches. List(JObject(List((abc,JString(1)), (de,JString(1)))), JObject(List((fgh,JString(2)), (ij,JString(4))))) JObject(List((abc,JString(1)), (de,JString(1)))) JString(1) JString(1) JObject(List((fgh,JString(2)), (ij,JString(4)))) JString(2) JString(4)Cinchonine
C
7

You should be able to either cast to JArray

val myArray = myVal.asInstanceOf[JArray]
myArray.arr // the array

or preferably use a scala match so you can confirm the type is correct.

Caecilian answered 20/1, 2016 at 14:49 Comment(1)
I was about to get into a scala match nightmare to solve this. Like this, it's just perfect.Doersten

© 2022 - 2024 — McMap. All rights reserved.