Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to JsValue?

I'm trying to add in a new element to a JsValue, but I'm not sure how to go about it.

 val rJson = Json.parse(response)
 val imgId = //stuff to get the id :Long
 rJson.apply("imgId", imgId) 
 Json.stringify(rJson)

Should I be converting to a JSONObject or is there some method that can be applied directly to the JsValue to insert a new element to the JSON?

Edit:

response is coming from another server, but I do have control over it. So, if I need to add an empty "imgId" element to the JSON Object, that's fine.

like image 945
bad at scala Avatar asked Dec 04 '22 05:12

bad at scala


1 Answers

You can do this as a JsObject, which extends JsValue and has a + method:

val rJson: JsValue = Json.parse(response)
val imgId = ...
val returnJson: JsObject = rJson.as[JsObject] + ("imgId" -> Json.toJson(imgId))
Json.stringify(returnJson)
like image 121
Michael Zajac Avatar answered Dec 19 '22 08:12

Michael Zajac