Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created December 4, 2018 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/99a08a09d7b5d25a2828f3d497ff244c to your computer and use it in GitHub Desktop.
Save fancellu/99a08a09d7b5d25a2828f3d497ff244c to your computer and use it in GitHub Desktop.
Scala uJson code to censor certain field names
import ujson.{ Obj, Value }
object Censor{
def updateAll(root: Value, target: (String => Boolean), newValue: Value): Value = {
def update(value: Value, parent: Value = null, valueName: String = null): Unit = {
value match {
case Obj(values) =>
values.map { case (name, v) => update(v, value, name) }
case _ =>
if (target(valueName)) parent(valueName) = newValue
}
}
update(root)
root
}
}
val raw=""" {
| "stuff" : {
| "password": [1,2,3]
| },
| "password" : "value1",
| "key2" : {
| "password" : 1233333,
| "key23" : [ "alpha", "beta", "gamma"],
| "key24" : {
| "password": true,
| "key242" : "value242",
| "confirmPassword": "dontshowthis"
| }
| }
|}""".stripMargin
val playjson: JsValue = Json.parse(raw)
//updateAll(json2,_=="password", "****cen***") // single field
updateAll(playjson,Set("password","confirmPassword"), "****cen***") // set, which is of course a predicate also
{
"stuff": {
"password": "****cen***"
},
"password": "****cen***",
"key2": {
"password": "****cen***",
"key23": [
"alpha",
"beta",
"gamma"
],
"key24": {
"password": "****cen***",
"key242": "value242",
"confirmPassword": "****cen***"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment