Play框架:如何替换JSON树中所有出现的值 [英] Play Framework: How to replace all the occurrence of a value in a JSON tree

查看:106
本文介绍了Play框架:如何替换JSON树中所有出现的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下JSON ...

Given the following JSON...

{ "id":"1234",
  "name" -> "joe",
  "tokens: [{
     "id":"1234",
     "id":"2345"
   }]
}

...我需要像这样用xxxx替换所有id的值:

... I need to replace the value of all the ids by xxxx like this:

{ "id":"xxxx",
  "name" -> "joe",
  "tokens: [{
     "id":"xxxx",
     "id":"xxxx"
   }]
}

让我们开始创建JSON树:

Let's start create the JSON tree:

val json = Json.obj(
  "id" -> "1234",
  "name" -> "joe",
  "tokens" -> Json.arr(
     Json.obj("id" -> "1234"),
     Json.obj("id" -> "2345")
  )
)

json: play.api.libs.json.JsObject = {"id":"1234","name":"joe","tokens":[{"id":"1234"},{"id":"2345"}]}

然后,获取所有id非常简单:

Then, getting all the ids is very simple:

 json \\ "id"

 res64: Seq[play.api.libs.json.JsValue] = List("1234", "1234", "2345")

现在,如何用xxxx替换所有id的值?

Now, how do I replace the value of all the ids by xxxx?

推荐答案

使用标准的JSON播放库似乎没有一种很好的方法,尽管我很乐意被证明是错误的.但是,您可以使用 play-json-zipper 扩展名轻松地做到这一点:

There doesn't appear to be a nice way to do this with the standard Play JSON library, although I'd be happy to be proved wrong in that regard. You can however do it easily using the play-json-zipper extensions:

import play.api.libs.json._
import play.api.libs.json.extensions._

val json = Json.obj(
  "id" -> "1234",
  "name" -> "joe",
  "tokens" -> Json.arr(
    Json.obj("id" -> "1234"),
    Json.obj("id" -> "2345")
  )
)

// Using `updateAll` we pattern match on a path (ignoring
// the existing value, as long as it's a string) and replace it
val transformed = json.updateAll {
  case (__ \ "id", JsString(_)) => JsString("xxxx")
}

// play.api.libs.json.JsValue = {"id":"xxxx","name":"joe","tokens":[{"id":"xxxx"},{"id":"xxxx"}]}

要使该功能可重用:

def replaceValue(json: JsValue, key: String, replacement: String) = json.updateAll {
  case (__ \ path, JsString(_)) if path == key => JsString(replacement)
}

json-zipper扩展仍然是实验性的",但是如果要将它们添加到项目中,请在project/Build.scala appDependencies中添加以下内容:

The json-zipper extensions are still "experimental", but if you want to add them to your project add the following to your project/Build.scala appDependencies:

"play-json-zipper" %% "play-json-zipper" % "1.0"

和以下解析器:

"Mandubian repository releases" at "https://github.com/mandubian/mandubian-mvn/raw/master/releases/"

这篇关于Play框架:如何替换JSON树中所有出现的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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