Home > Net >  Nested maps with different structure
Nested maps with different structure

Time:10-27

I am new to Scala and I want to build an object that looks like below and then convert to Json, but doing something like this gives me error. How can I achieve this?

This is what I tried:

Map(a -> Map(b-> "1", c -> "2"),
Map(d -> values.map(v => Map(b-> v.value1, c -> v.value2)))
.asJson

Expected outcome:

{
"a":{"b": "1", "c": "2"},
"d":[{"b":"x1","c":"x2"},{"b":x3,"c":"x4"}...]
}

CodePudding user response:

You should reserve to using the JSON library's provided DSL instead, i.e. circe JSON DSL:

import io.circe.Json
import io.circe.syntax.*

Json.obj(
  "a" := Json.obj("b" := "1", "c" := "2")
  "d" := values.map(v => Json.obj("b" := v.value1, "c" := v.value2))
)
  • Related