Play-json: Error on updating an object attribute i

2019-09-09 12:47发布

问题:

I am playing with play-json library to manipulate my json files. I have followed this official document and everything is working fine but they haven't told the case when we want to update a value of an object inside an array so I am trying this my own example.

i.e.

[
  {
    "key1": [
      {
        "key12": [
          {
            "key121": "text1",
            "key122": 121212,
            "key123": "text2",
            "key124": []
          }
        ],
        "key13": 0
      }
    ],
    "key2": "value2"
  }
]

In above example I am trying to update value of "key123" but getting this error again and again, just not able to find out where am I doing wrong:(

Exception in thread "main" java.util.NoSuchElementException: JsError.get at play.api.libs.json.JsError.get(JsResult.scala:14) at play.api.libs.json.JsError.get(JsResult.scala:13) at Refactor.authPage(Refactor.scala:73) at Builder$.main(Builder.scala:36) at Builder.main(Builder.scala) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Here is my code. Any kind of help would be appreciated.

val transform = (((__ (0) \ 'key1)(0) \ 'key12)(0) \ 'key123).json.update(__.read[JsString].map(x => JsString("updated")))

val jsValue = Json.parse("example.json").transform(transform).get

回答1:

I have done some research on internet and found that this issue has been already discussed on play mailing list, even there was a ticket to fix this problem. play-json has no native support to update value inside an array (you can do but it would then require lot of handful work, you need to update complete JsArray).

However play-json has no current support for transformation based on array indices, there is a helper-library play-json-zipper, which support all such feature and a little more. Play developers have closed the above mentioned ticket, assuming people can use play-json-zipper if required.

P.S: Adding my own answer so that if anyone else lands here by google search they can easily find the solution.