Add item to JsValue?

I'm trying to add a new item to JsValue, but I'm not sure how to do this.

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

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

Edit:

responsecoming from another server, but I have control over it. So, if I need to add an empty object "imgId"to a JSON object, that’s fine.

+4
source share
2 answers

You can do this as JsObjectwhich extends JsValueand has a method +:

val rJson: JsValue = Json.parse(response)
val imgId = ...
val returnJson: JsObject = rJson.as[JsObject] + ("imgId" -> Json.toJson(imgId))
Json.stringify(returnJson)
+8
source

I use the following helper in the project I'm working on:

/** Insert a new value at the given path */
def insert(path: JsPath, value: JsValue) =
  __.json.update(path.json.put(value))

JSON :

val rJson = Json.parse(response)
val imgId = //stuff to get the id :Long
Json.stringify(rJson.transform(insert(__ \ 'imgId, imgId)))

insert, , API- .

, andThen. API , Reads . insert API, , , API.

, API , Play framework docs JSON, 5 , , .

+5

All Articles