Home > Software design >  Converting JSON into Seq<String> in Scala
Converting JSON into Seq<String> in Scala

Time:07-04

I'm new in Scala and trying to achieve the following using Scala's foldLeft() method or any other functional solution:

I have the following JSON:

 {
   "aspects": [
     {
       "name": "Name",
       "values": [
         "Phone"
       ]
     },
     {
       "name": "Color",
       "values": [
         "Red",
         "Black"
       ]
     },
     {
       "name": "Size",
       "values": [
         "6",
         "10"
       ]
     }
   ]
 }

I want to convert this into the following Seq<String>:

["Name:::Phone", "Color:::Red", "Color:::Black", "Size:::6", "Size:::10"]

I did that using Java style where aspects is an object representing the JSON:

 aspects.foreach(pair => {
   pair.values.foreach(value => {
     valuesList  = pair.name   ":::"   value
   })
 })

What is the best Scala's way to do this?

CodePudding user response:

It depends on the JSON library you are using, but once you have the aspects data in a suitable format the output can be generated is like this:

case class Aspect(name: String, values: Seq[String])

val aspects: Seq[Aspect] = ???

aspects.flatMap(a => a.values.map(a.name   ":::"   _))

I use json4s and jackson and the conversion code is basically just

val aspects = parse(json).extract[Seq[Aspect]]

Check the documentation for details, and check out other JSON libraries which may be more suitable for your application.

CodePudding user response:

Have not parsed the JSON since the object aspects has these values. Just manually constructing the case class and flatmapping it

scala> final case class Aspects(pairs:Seq[Pair])
defined class Aspects

 val namepair = Pair("Name",Seq("Phone"))
namepair: Pair = Pair(Name,List(Phone))

 val colorpair = Pair("Color",Seq("Red","Black"))
colorpair: Pair = Pair(Color,List(Red, Black))

 val sizepair = Pair("Size",Seq("6","10"))
sizepair: Pair = Pair(Size,List(6, 10))

 val aspects = Aspects(Seq(namepair,colorpair,sizepair))
aspects: Aspects = Aspects(List(Pair(Name,List(Phone)), Pair(Color,List(Red, Black)), Pair(Size,List(6, 10))))

aspects.pairs.flatMap(pair=>pair.values.map(value=>s"${pair.name}:::$value"))
res1: Seq[String] = List(Name:::Phone, Color:::Red, Color:::Black, Size:::6, Size:::10)
  • Related