0

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"}...]
}
4
  • In general, you would want to model your data using case class and then convert that to a Json, or if this is something used in a single place then you may indeed consider using the Json type provided by your library rather than using an heterogeneous map. Commented Oct 26, 2022 at 13:00
  • you are right @AndriyPlokhotnyuk Updated Commented Oct 26, 2022 at 17:57
  • It is used in just one place. What do you mean by "your library" @LuisMiguelMejíaSuárez? can you provide any example? Commented Oct 26, 2022 at 17:59
  • You are using some kind of library to manage JSON, be it circe, uPickle, zio-json, etc. Each one of those would have a proper way to build a Json object, just like the accepted answer shows how to do it using circe. Commented Oct 26, 2022 at 18:42

1 Answer 1

2

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))
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.