I'm in the process of choosing a good Scala JSON library, and the consensus seems to be that lift-json
is currently the best choice.
After playing with it (version 2.5.1) for a spell, I've been able to do most of the things I needed fairly easily, except for one: modifying an existing JValue
.
Say that I have the following instance of JValue
:
val john = ("id" -> 1) ~
("name" -> "Foo") ~
("nested" ->
("id" -> 2) ~
("name" -> "Bar"))
I'd like to change the parent element's name from Foo
to foo
. I thought the transform
method was the way to go:
john transform {
case JField("name", _) => JField("name", "foo")
})
But this changes both the parent and nested element's name
fields to foo
- which, in retrospect, really should not have been a surprise.
I've looked at the documentation and code and could not find a way to choose a specific field with a key of name
. Did I miss something?
The other solution (and this one works) seems to be merging two JValue
objects, but it seems a bit verbose:
john merge JObject(JField("name", "foo") :: Nil)
Is there a built-in, more readable way of achieving the same result? I probably could write an implicit conversion from JField
to JObject
, but it seems odd that lift-json
doesn't already have such a mechanism. If I had to bet, it'd be on my not having found it rather than on it not existing.
EDIT: I feel a bit silly now
john transform {
case JField("name", "Foo") => JField("name", "foo")
})
Not the most optimal solution in the world, but perfectly readable and concise.