-3

JSON FILE: need to iterate each element using scala.read the JSON file in scala and iterate over the each element & and add it the particular list.

Input:

{"details": [{"Level": "1", "member": "age", "claim": "age"}, {"Level": "2", "member": "dob", "claim": "dob"}, {"Level": "2", "member": "name", "claim": "name"}]}

output:

Memberlist=list(list(age),list(dob),list(name))

Claimlist=list(list(age),list(dob),list(name))

vijay
  • 1
  • 9

2 Answers2

0

You can use simple and recursive path to traverse JSON objects in Scala, assuming you're using the Play Framework

val jsonDetails:JsValue = Json.parse("""
{"details":
[{"Level": "1", "member":"age", "claim":"age"},
 {"Level": "2", "member": "dob", "claim": "dob2"},
 {"Level": "2", "member":"name1", "claim":"name"}
]}
""")
var pathToFirstLevel = (jsonDetails\"details"\0\"Level")
var allIstancesOfMember = (jsonDetails\\"member")

Will return

res1: play.api.libs.json.JsLookupResult = JsDefined("1")
res2: Seq[play.api.libs.json.JsValue] = List("age", "dob", "name1")

You can grab the data you're looking for and populate your lists, but you'll need to convert the JsValues to values Scala can work with (use .as[T] not asInstanceOf[T])

You can also use map

var allIstancesOfMember =(jsonDetails\\"member").map(_.as[String])

There's loads of information on traversing JSON elements in Scala using the Play Framework at https://www.playframework.com/documentation/2.6.x/ScalaJson

does that answer your question?

Andro
  • 1
  • 1
  • 3
0

Not sure whether this solution can fit for your requirement.

Some concrete classes used for extraction

class CC[T] { def unapply(a:Any):Option[T] = Some(a.asInstanceOf[T]) }

object M extends CC[Map[String, Any]]
object L extends CC[List[Any]]
object S extends CC[String]

ListBuffer for output.

val memberList = ListBuffer.empty[Any]
val claimList = ListBuffer.empty[Any]

for comprehension to iterate over list of details and extract each detail.

for {
     Some(M(map)) <- List(JSON.parseFull(s))
     L(details) = map("details")
     M(language) <- details
     //S(level) = language("Level") //Not so sure how to use this variable
     S(member) = language("member")
     S(claim) = language("claim")
     } yield {
         memberList += List(member) //List is used to match your output.
         claimList += List(claim)  //List is used to match your output.
     }

Output

println(memberList) 
//ListBuffer(List(m_age), List(m_dob), List(m_name))
println(claimList)
//ListBuffer(List(c_age), List(c_dob), List(c_name))

Credits to this answer

Puneeth Reddy V
  • 1,538
  • 13
  • 28