如何使用 Scala Play 框架更新嵌套的 json? [英] How to update a nested json using scala play framework?

查看:57
本文介绍了如何使用 Scala Play 框架更新嵌套的 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Scala play 框架更新 json 中存在的 json 值.它不是更新值而是附加值.

I am trying to update a json value present within a json using Scala play framework.Instead of updating the value it is appending the value.

val newJsonString = """{"P123": 25}"""
val jsonStringAsJsValue = Json.parse("""{"counter_holders": {"Peter": 25}}""")
//jsonStringAsJsValue: play.api.libs.json.JsValue = {"counter_holders":{"Peter":25}}

val jsonTransformer = (__ \"counter_holders" ).json.update(__.read[JsValue].map{o => Json.parse(newJsonString)})

jsonStringAsJsValue.transform(jsonTransformer).get.as[JsValue]
//Now getting this jsvalue
//play.api.libs.json.JsValue = {"counter_holders":{"Peter":25,"P123":25}}
//But need  this jsvalue
//play.api.libs.json.JsValue = {"counter_holders":{"P123":25}}

对此的任何帮助都会非常好.

Any help on this will be really nice.

推荐答案

引用自 update 方法文档:

(__ \ 'key).json.update(reads) 是最复杂的 Reads[JsObject]但最强大的:

(__ \ 'key).json.update(reads) is the most complex Reads[JsObject] but the most powerful:

  • 复制整个 JsValue =>一个

  • copies the whole JsValue => A

将传递的 Reads[A] 应用到 JsValue =>乙

applies the passed Reads[A] on JsValue => B

deep 合并两个 JsValues (A ++ B) 所以 B 覆盖 A 相同的分支 请注意,如果你在 B 中修剪了一个分支,它仍然是在 A 中,您将在结果中看到它 示例:

deep merges both JsValues (A ++ B) so B overwrites A identical branches Please note that if you have prune a branch in B, it is still in A so you'll see it in the result Example:

{{{ val js = Json.obj("key1" -> "value1", "key2" -> "value2")
js.validate(__.json.update((__ \ 'key3).json.put(JsString("value3"))))
=> JsSuccess({"key1":"value1","key2":"value2","key3":"value3"},) }}}

因此,您看到的行为符合预期.如果你想采用这种方法,使用路径更新,你可以使用方法 修剪.例如你可以这样做:

Therefore the behaviour you see is as expected. If you want to take that approach, of updating using the path, you can use the method prune. For example you can do:

val newJsonString = """{"P123": 25}"""
val jsonStringAsJsValue = Json.parse("""{"counter_holders": {"Peter": 25}}""")
//jsonStringAsJsValue: play.api.libs.json.JsValue = {"counter_holders":{"Peter":25}}

val jsonTransformer = (__ \"counter_holders" ).json
  .update(__.read[JsValue].map{o => Json.parse(newJsonString)})

val jsonTransformerDelete = (__ \"counter_holders" \ "Peter" ).json.prune

jsonStringAsJsValue.transform(jsonTransformer).flatMap(_.transform(jsonTransformerDelete)) match {
  case JsSuccess(value, _) =>
    println(value)
  case JsError(errors) =>
    println(errors)
}

这将产生想要的行为.您可以在 scastie 中找到它.

which will produce the wanted behaviour. You can find it in scastie.

这篇关于如何使用 Scala Play 框架更新嵌套的 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆