Create a json object and adding new key, value pairs to it

1.3k views Asked by At

I've a scala Map which is of form <String, Any>. My objective is to iterate over all the key of the map and create a new json object which consists of all these k,v pairs. I'm using play framework for the json library.

I tried this:

var out  = JsNull
for (str <- inp) {
    out = out.as[JsObject] + (str -> Json.toJson(inp(str)))
}

However Json.toJson returns a JsonNode whereas it is expecting a JsValue. I've looked at this SO Question for adding new items.

Question 1: How do I convert JsonNode to JsValue

Question 2: This is a bad implementation in scala. I'm using var. How do I convert the same logic so that I use a val. I'm particularly new to functional programming, so have a tough time thinking away from the usual iterative loops.

0

There are 0 answers