Validation Only With Play Json - scala

I'd like to use PlayJson to only validate multiple fields of some json and not map it to a custom object. I Only care about the Yes Or No answer to the validation criteria. Is it possible to use PlayJson in that way? So far I have something like,
val json = .....
val reads = (JsPath \ "foo").read[String](min(5)) and
(JsPath \ "bar").read[String](max(10))
json.validate["I ONLY WANT TO VALIDATE NOT MAP"](reads) match {
case s: JsSuccess => true
case e: JsError => false
}
Thank you Stack Overflow community.

Instead of deserialising to a case class model via Reads[MyModel] we can deserialise to a tuple via Reads[(String, String)] like so
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
val reads = (
(JsPath \ "foo").read[String](minLength[String](5)) and
(JsPath \ "bar").read[String](minLength[String](10))
).tupled
val json = Json.parse(
"""
|{
| "foo": "abcde",
| "bar": "woohoowoohoo",
| "zar": 42
|}
|""".stripMargin)
json.validate(reads).isSuccess
which outputs
res0: Boolean = true
Note how we called tupled method when creating the reader, and isSuccess to get a boolean out of validation process.
https://scalafiddle.io/sf/JBjdt2Y/0

Related

Transform Value In PlayJSon Mapping

I'm performing a standard mapping of JSON to a case class using PlayJson. I'd like to transform the value that gets mapped to a member, Test.foo below, if the validation succeeds. Is it possible to work that into the definition of a Reads converter?
val json = .....
case class Test(foo:String, bar:String)
val readsTest: Reads[Test] = (
(__ \ "foo").read[String](minLength(5)) and // And I want to transform this value if the validation succeeds
(__ \ "bar").read[String](minLength(10))
)(Test.apply _)
json.validate[Test] match {
case s: JsSuccess[Test] => s.get
case e: JsError => false
}
Reads.map can do just that, for example, say we want to reverse the value of foo field, then we could call .map(v => v.reverse) on the Reads like so
(__ \ "foo").read[String](minLength[String](5)).map(v => v.reverse)
Here is a working example
val json =
"""
|{
| "foo": "abcdefghijkl",
| "bar": "012345678910"
|}
|""".stripMargin
case class Test(foo: String, bar: String)
val readsTest: Reads[Test] = (
(__ \ "foo").read[String](minLength[String](5)).map(v => v.reverse)
(__ \ "bar").read[String](minLength[String](10))
)(Test.apply _)
Json.parse(json).validate[Test](readsTest)
which outputs
JsSuccess(Test(lkjihgfedcba,012345678910),)

Handling non-default nested Json Reads

So I have following JSON:
{
"senderEmail" : "sender#email.com",
"recipientEmails" : ["first#email.com", "second#email.com"]
}
and would like to map it to case class:
case class Payload (senderEmail: String, recipientEmails: Seq[String])
using Play's Json Reads with email validator.
While it's trivial for a senderEmail, I'm having trouble with recipientEmails since it's both Seq and email so this will not work:
implicit val payloadRead: Reads[Payload] = (
(JsPath \ "senderEmail").read[String](Reads.email) and
(JsPath \ "recipientEmails").read[Seq[String]](Reads.seq))(Payload.apply _)
I'm getting overloaded method value read with alternatives.
So how can I combine both Reads.seq and Reads.email?
Just keep it simple ...
scala> import play.api.libs.json._
scala> import play.api.libs.functional.syntax._
scala> case class Payload (senderEmail: String, recipientEmails: Seq[String])
defined class Payload
scala> implicit val reads: Reads[Payload] = (
| (JsPath \ "senderEmail").read(Reads.email) and
| (JsPath \ "recipientEmails").read(Reads.seq(Reads.email))
| )(Payload.apply _)
reads: play.api.libs.json.Reads[Payload] = play.api.libs.json.Reads$$...
scala> Json.parse("""{
| "senderEmail" : "sender#email.com",
| "recipientEmails" : ["first#email.com", "second#email.com"]
| }""").validate[Payload]
res0: play.api.libs.json.JsResult[Payload] = JsSuccess(Payload(sender#email.com,Vector(first#email.com, second#email.com)),)

Scala play framework: complex read to match multiple keys for same field in case class

i'm a scala newbie...
let's say i have a case class like this:
case class Event(name: Option[String]) {}
i want to use the Play framework to parse it. however, sometimes i get a json payload where the first letter of the key is uppercase and sometimes lowercase. like so:
lowercase
{
"name": "group_unsubscribe",
}
uppercase
{
"Name": "group_unsubscribe",
}
how can i account for these possibilities using a complex reads?
i have tried with things like:
implicit val reads: Reads[Event] = (
((JsPath \ "name").readNullable[String] or
(JsPath \ "Name").readNullable[String])
)(Event.apply _)
but no joy :(
You need to re-write your Reads as:
implicit val reads: Reads[Event] = (
(JsPath \ "name").readNullable[String] orElse
(JsPath \ "Name").readNullable[String]
).map(Event(_))
Update 1 taking into account the comments:
import play.api.libs.json.Reads
implicit val reads: Reads[Event] = (
(JsPath \ "name").read[String] orElse
(JsPath \ "Name").read[String]
).map(name => Event(Option(name)))
Note: this implementation assumes that either "name" or "Name" will always be present in the incoming JSON document.
In order to capture the possibility of failure, you should use .validate[T] instead of .as[T].
Update 2 taking into account further comments:
Whether you have one or more attributes in your type doesn't change much. If your type had another field called somethingElse you would need to adapt your Reads to something like:
implicit val reads: Reads[Event] = (
((JsPath \ "name").read[String] orElse
(JsPath \ "Name").read[String]).map(Option(_)) ~
(JsPath \ "somethingElse").read[String]
)(Event.apply _)

How to read json array in scala using the Play framework

I have the following Json as var dataObject ={"files": ["code.R", "data.cv", "input.txt"]}.
I am posting this json as a body from the client side and I want to parse the Json and read these files names in the server side in play scala.
Please help
Because you have only one field, you can't use json combinators,
But you can do as follow:
case class Selection(files:List[String])
object Selection{
implicit val selectionReads = (__ \ 'files).read[List[String]].map{ l => Selection(l) }
implicit val selectionWrites = (__ \ 'files).write[List[String]].contramap { (selection: Selection) => selection.files}
//You can replace the above 2 lines with this line - depends on you.
implicit val selectionFormat: Format[Selection] = (__ \ 'files).format[List[String]].inmap(files => Selection(files), (selection: Selection) => selection.files)
}
Make sure you import:
import play.api.libs.functional.syntax._
This is the documentation: https://www.playframework.com/documentation/2.5.x/ScalaJson
And the solution is simple:
import play.api.libs.json._
val json: JsValue = Json.parse("{ "files": ["code.R","data.csv","input.txt"] }")
val files = (json \ "files").get

How to Manipulate JSON AST in Scala

I am experimenting with the json4s library (based on lift-json). One of the things I would like to do is to parse a JSON string into an AST, and then manipulate it.
For example, I would like to upsert a field (insert the field into the AST if it does not exist, or update its value if it does).
I have not been able to find how to do it in the documentation. Experimenting with the available methods, I have come up with the following, which works, but feels clumsy.
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
object TestJson {
implicit val formats = DefaultFormats
def main(args: Array[String]): Unit = {
val json = """{"foo":1, "bar":{"foo":2}}"""
val ast = parse(json).asInstanceOf[JObject]
println( upsertField(ast, ("foo" -> "3")) )
println( upsertField(ast, ("foobar" -> "3")) )
}
def upsertField(src:JObject, fld:JField): JValue = {
if(src \ fld._1 == JNothing){
src ~ fld
}
else{
src.replace(List(fld._1), fld._2)
}
}
}
I dislike it for many reasons:
Having to explicitly cast the results of parse(json) to JObject
The result of the upsertField function is a JValue, which I will have to recast if I want to manipulate the object further
The upsertField function just feels very unelegant
It does not work for fields that are not at the top level of the hierarchy
Is there a better way to transform the AST?
EDIT: as a workaround to the problem, I have managed to convert my JSON to Scala regular classes, and manipulate them with lenses (Using Lenses on Scala Regular Classes)
There is the merge function which creates or overrides a field. You can also update fields that are not at the root level of the tree.
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
object mergeJson extends App {
val json =
"""
|{
| "foo":1,
| "bar": {
| "foo": 2
| }
|}
|""".stripMargin
val ast = parse(json)
val updated = ast merge (("foo", 3) ~ ("bar", ("fnord", 5)))
println(pretty(updated))
// {
// "foo" : 3,
// "bar" : {
// "foo" : 2,
// "fnord" : 5
// }
// }
}
Let me also give you the SON of JSON version:
import nl.typeset.sonofjson._
val json = parse("""{ "foo" : 1, "bar" : { "foo" : 2 } }""")
// or, perhaps a little easier
val json = obj(foo = 1, bar = obj(foo = 2))
json.foo = "3"
json.foobar = "3"
When I was implementing some very specific json diff using lift json I used a lot of recursive functions to get to the jpath where I need to modify value, and modified json was constructed when recursion "collapsed". LiftJson is immutable after all. You mentioned lenses as another approach, which is very interesting by itself. But my current favourite is play-json library that is working like a charm in a situation when you need to do json-to-json transformation:
from Mandubian Blog:
val gizmo2gremlin = (
(__ \ 'name).json.put(JsString("gremlin")) and
(__ \ 'description).json.pickBranch(
(__ \ 'size).json.update( of[JsNumber].map{ case JsNumber(size) => JsNumber(size * 3) } ) and
(__ \ 'features).json.put( Json.arr("skinny", "ugly", "evil") ) and
(__ \ 'danger).json.put(JsString("always"))
reduce
) and
(__ \ 'hates).json.copyFrom( (__ \ 'loves).json.pick )
) reduce
Yummy Features: all transformers are combinators that can be mixed together, validation, shapeless support, auto marshaling of case classes with implicit overrides, stand-alone library.