Reputation: 69
the question is not specific for JsValue, its for all the immutable objects in scala which i want to edit part of it and keep the rest as is. for example i have this object:
"references": {
"hsId": "37395615-244b-4706-b6f5-237272f07140",
"others": {
"path": "rewr",
"externalId": "ewr",
"version": "2"
}
}
and lets say i just want to edit the version.
thanks
Upvotes: 1
Views: 1475
Reputation: 55569
You could use JSON transformers. Let's say we want to change the version to "3"
.
val js: JsValue = Json.parse("""
{
"references": {
"hsId": "37395615-244b-4706-b6f5-237272f07140",
"others": {
"path": "rewr",
"externalId": "ewr",
"version": "2"
}
}
}
""")
// Define the transformer
val transformer = (__ \ "references" \ "others").json.update(
__.read[JsObject].map{o => o ++ Json.obj("version" -> "3")}
)
val newJs = js.transform(transformer)
This will copy the entire object, then replace version
on the others
branch.
Upvotes: 1
Reputation: 69
ok i figured out a way of solution, but i feel its a patch and not the best answer
val references: JsObject = (json \ "references").as[JsObject]
val newVersion = JsObject(List(("others", JsObject(List(("version", JsString("3")))).as[JsValue])))
val newReferences = references.deepMerge(newVersion)
Upvotes: 1