Home > Software engineering >  How to parse multiple lists into array of json objects, using Scala?
How to parse multiple lists into array of json objects, using Scala?

Time:04-30

How to convert multiple Lists (with equal number of elements) into Array of JSON Objects, using Scala?

Given:

List("Rec Type", "Evnt Type", "B/S Cd", "Sym"), 
List("cmn_rec_type", "cmn_event_type_cd", "cmn_buy_sell_cd", "cmn_issue_sym_id"),
List("Record Type", "Event Type", "Buy Sell Code", "Issue Symbol ID"),
List("Common", "Common", "Common", "Common", "Common")

Convert into:

[
{
"name":"Rec Type",
"id":"cmn_rec_type",
"description": "Record Type",
"recordType":"Common"
},
{
"name":"Evnt Type",
"id":"cmn_event_type_cd",
"description":"Event Type",
"recordType":"Common"
},
{
"name":"B/S Cd",
"id":"cmn_buy_sell_cd",
"description":"Buy Sell Code",
"recordType":"Common"
},
{
"name":"Sym",
"id":"cmn_issue_sym_id",
"description":"Issue Symbol ID",
"recordType":"Common"
}
]

CodePudding user response:

This would work:

listOrLists.transpose.map { case name :: id :: description :: recordType :: _ =>
  raw"""{ "name": "$name"
       |, "id": "$id"
       |, "description": "$description"
       |, "recordType": "$recordType"
       |}""".stripMargin
}.mkString("[", ",", "]")
  • Related