surbhi khare
surbhi khare

Reputation: 19

Create a json from a list of Map in Scala Circe

I have a list of Map like this:

List(Map(id -> 1, weight -> 38), Map(id -> 4, weight -> 98), Map(id -> 4, weight -> 66), Map(id -> 6, weight -> 89))

I would like to create a json from above map using Scala - with circe like this

{
  "id":1,
  "weight":38
},
{
"id":4,
"weight":98
}

Upvotes: 0

Views: 1823

Answers (1)

Alexey Novakov
Alexey Novakov

Reputation: 764

You would need to add such Circe dependency: io.circe::circe-core:0.14.1


import io.circe.syntax._

val l = List(
  Map("id" -> 1, "weight" -> 38), 
  Map("id" -> 4, "weight" -> 98), 
  Map("id" -> 4, "weight" -> 66), 
  Map("id" -> 6, "weight" -> 89)
)

// and then
val jsonStr = l.asJson.noSpaces
println(jsonStr)
"[{\"id\":1,\"weight\":38},{\"id\":4,\"weight\":98},{\"id\":4,\"weight\":66},{\"id\":6,\"weight\":89}]"

Upvotes: 3

Related Questions