Skip to content

Instantly share code, notes, and snippets.

@jeantil
Last active August 29, 2015 14:00
Show Gist options
  • Save jeantil/11282948 to your computer and use it in GitHub Desktop.
Save jeantil/11282948 to your computer and use it in GitHub Desktop.
Helpers for json manipulation with play-json
package libs.json
object JsonOperations {
import play.api.libs.json._
def withDefault[A](key: String, default: A)(implicit writes: Writes[A]) = __.json.update((__ \ key).json.copyFrom((__ \ key).json.pick orElse Reads.pure(Json.toJson(default))))
def copyKey(fromPath: JsPath,toPath:JsPath ) = __.json.update(toPath.json.copyFrom(fromPath.json.pick))
def copyOptKey(fromPath: JsPath,toPath:JsPath ) = __.json.update(toPath.json.copyFrom(fromPath.json.pick orElse Reads.pure(JsNull)))
def moveKeyWrites(fromPath:JsPath, toPath:JsPath) =(json:JsValue)=> json.transform(moveKeyReads(fromPath,toPath)).get
def moveKeyReads(fromPath:JsPath, toPath:JsPath) =copyKey(fromPath,toPath) andThen fromPath.json.prune
def inflateKey(keyName: Symbol) = __.json.update((__ \ 'version \ keyName).json.copyFrom((__ \ keyName).json.pick))
def inflateOptKey(keyName: Symbol) = __.json.update((__ \ 'version \ keyName).json.copyFrom((__ \ keyName).json.pick orElse Reads.pure(JsNull)))
def flattenKey(keyName: Symbol) = __.json.update((__ \ keyName).json.copyFrom((__ \ 'version \ keyName).json.pick))
def flattenOptKey(keyName: Symbol) = __.json.update((__ \ keyName).json.copyFrom((__ \ 'version \ keyName).json.pick orElse Reads.pure(JsNull)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment