Skip to content

Commit 2bf20cb

Browse files
authored
Fix issue with lost siblings when modifying at some path (#3)
1 parent 0e8d623 commit 2bf20cb

2 files changed

Lines changed: 36 additions & 11 deletions

File tree

src/main/scala/nl/vroste/playjsonoptics/JsLens.scala

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -75,17 +75,16 @@ object JsLens {
7575
private def optionalValueAtPath(path: JsPath): Lens[JsValue, Option[JsValue]] =
7676
Lens[JsValue, Option[JsValue]](path.asSingleJsResult(_).asOpt) {
7777
newValueOpt =>
78-
root =>
79-
root match {
80-
case rootObj@JsObject(_) =>
81-
newValueOpt match {
82-
case Some(obj) =>
83-
rootObj ++ JsPath.createObj((path, obj))
84-
case None =>
85-
path.json.prune.reads(rootObj).getOrElse(rootObj)
86-
}
87-
case _ => root
88-
}
78+
{
79+
case rootObj@JsObject(_) =>
80+
newValueOpt match {
81+
case Some(obj) =>
82+
rootObj deepMerge JsPath.createObj((path, obj))
83+
case None =>
84+
path.json.prune.reads(rootObj).getOrElse(rootObj)
85+
}
86+
case root => root
87+
}
8988
}
9089

9190
// Allows remove syntax

src/test/scala/nl/vroste/playjsonoptics/JsLensSpec.scala

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,32 @@ class JsLensSpec extends FlatSpec with MustMatchers with Inside with OptionValue
7979
optic.modify(_ + "X")(json) mustBe expectedJson
8080
}
8181

82+
it must "leave siblings intact when modifing at some path" in {
83+
val json = Json.parse(
84+
"""
85+
|{"a" : {
86+
| "b" : "someValue",
87+
| "c" : "otherValue"
88+
| }
89+
| }
90+
""".stripMargin
91+
)
92+
93+
val expectedJson = Json.parse(
94+
"""
95+
|{"a" : {
96+
| "b" : "someValue",
97+
| "c" : "otherValueadd"
98+
| }
99+
| }
100+
""".stripMargin
101+
)
102+
103+
val optic = JsLens[String](__ \ "a" \ "c")
104+
105+
optic.modify(_ + "add")(json) mustBe expectedJson
106+
}
107+
82108
"Removing at a given path" must "prune the JSON at that path" in {
83109
val json: JsValue = Json.obj(
84110
"field1" -> Json.obj(

0 commit comments

Comments
 (0)