ticofab
ticofab

Reputation: 7717

Scala + Play: serialize Map to Json Array

Imagine you have a Map[String, List[String]] that looks like this:

val myMap = Map(
   "ab" -> List("yo", "yo2", "yo3"),
   "cd" -> List("hi", "hi1", "hi2")
 )

if we do Json.toJson(myMap), the resulting JSON is

 {
   "ab" : ["yo", "yo2", "yo3"],
   "cd" : ["hi", "hi1", "hi2"]
 }

Is there a way we could get the outer container to be an array instead of an object? Like

 [
   "ab" : ["yo", "yo2", "yo3"],
   "cd" : ["hi", "hi1", "hi2"]
 ]

I'm not sure that this would be valid Json. Thanks.

Upvotes: 0

Views: 479

Answers (1)

Alexandr Dorokhin
Alexandr Dorokhin

Reputation: 850

The last one is not valid JSON. You could use Json.toJson(myMap.toList) to obtain result as @Tyth has answered. Actually Map is similar to Object of JSON format, cause it provides extracting values by key. In case with Array, it's reached over iterate over each element.

Upvotes: 1

Related Questions