logo
down
shadow

How to transform submitted json in Play 2.0?


How to transform submitted json in Play 2.0?

By : user2954031
Date : November 21 2020, 07:31 AM
hop of those help? You're basically dealing with a nested monad, and the main tool for working with such is flatMap, particularly if both options being None has the same semantic meaning to your program:
code :
request.body.asJson.flatMap { requestJson =>
  val repository = new UserRepository
  repository.findById(new UserId(id)).map { user =>
    def usernameAppender = __.json.update(
      __.read[JsObject].map { o => o ++ Json.obj("username" -> user.username) }
    )

    requestJson.transform(usernameAppender)

    Ok("updated") // EDIT: Do you not want to return the JSON?
  }
}.getOrElse(NotFound)
request.body.asJson match { 
  case Some(requestJson) =>
    val repository = new UserRepository
    repository.findById(new UserId(id)).map { user =>
      def usernameAppender = __.json.update(
        __.read[JsObject].map { o => o ++ Json.obj("username" -> user.username) }
      )

      requestJson.transform(usernameAppender)

      Ok("updated")
    }.getOrElse(NotFound)
  case None => BadRequest // Or whatever you response makes sense for this case
}


Share : facebook icon twitter icon
Why does text-transform in CSS not keep transform(uppercase) when submitted in form?

Why does text-transform in CSS not keep transform(uppercase) when submitted in form?


By : Alexander12
Date : March 29 2020, 07:55 AM
I wish this helpful for you CSS is only for presentation of content. Therefore it does not change the values entered by the user, or what is submitted by the form to your database.
If your business requirement is to only accept all uppercase values into the database, it would be best to handle this in the back-end. For example: $input = strtoupper($input); if using PHP. Doing this on the back-end will ensure that your processing occurs even if the user has JavaScript turned off.
How to transform any JSON string to Map[Symbol, Any] using import play.api.libs.json?

How to transform any JSON string to Map[Symbol, Any] using import play.api.libs.json?


By : user2014224
Date : March 29 2020, 07:55 AM
like below fixes the issue JsObject.fieldSet will give you a Set[(String, JsValue)] that you can transform into a Map[Symbol, Any]. You will have to pattern match on all possible subclasses of JsValue and transform each to the type you want.
For example, something like this:
code :
 Json.parse(text) match {

    case js: JsObject => 
      js.fieldSet.map { 
        case (key, value) => Symbol(key) -> transform(value) 
      }.toMap

    case x => throw new RuntimeException(s"Expected object json but got $text")
 }

 def transform(jsValue): Any = jsValue match {
    case JsNumber(value) => value.toDouble
    ...ect...
 }
Play 2.x Json transform json keys to camelCase from underscore case

Play 2.x Json transform json keys to camelCase from underscore case


By : Helmut_Grey
Date : March 29 2020, 07:55 AM
like below fixes the issue While it would be nice to do this with just the native Play library, it's a good use-case for Mandubian's Play Json Zipper extension libraries.
Here's a quick go at this (not exhaustively tested). First you need to add the resolver and library to your build:
code :
resolvers += "mandubian maven bintray" at "http://dl.bintray.com/mandubian/maven"

libraryDependencies ++= Seq(
  "com.mandubian"     %% "play-json-zipper"    % "1.2"
)
import play.api.libs.json._
import play.api.libs.json.extensions._

// conversion function borrowed from here:
// https://gist.github.com/sidharthkuruvila/3154845
def underscoreToCamel(name: String) = "_([a-z\\d])".r.replaceAllIn(name, {m =>
  m.group(1).toUpperCase
})

// Update the key, otherwise ignore them...
// FIXME: The None case shouldn't happen here so maybe we
// don't need it...
def underscoreToCamelCaseJs(json: JsValue) = json.updateAllKeyNodes {
  case (path, js) => JsPathExtension.hasKey(path) match {
    case Some(key) => underscoreToCamel(key) -> js
    case None => path.toJsonString -> js
  }
}
val testJson = Json.obj(
  "some_str" -> JsString("foo_bar"),
  "some_obj" -> Json.obj(
    "some_field" -> Json.arr("foo", "bar")
  ),
  "an_int" -> JsNumber(1)
)
{
  "someStr" : "foo_bar",
  "someObj" : {
    "someField" : [ "foo", "bar" ]
  },
  "anInt" : 1
}
Play Framework Json Transform recursivly

Play Framework Json Transform recursivly


By : TinkerBel
Date : March 29 2020, 07:55 AM
seems to work fine Just add the recursive call inside your Reads and make sure to handle JsArray as well as JsObject. Here is a simple example which fits this basic idea.
code :
val idChanger: Reads[JsObject] =
  (__ \ 'id).json.update(of[JsNumber].map{case JsNumber(nb) => JsNumber(nb * 100)})


val picker: Reads[JsValue] = __.json.pick.map{
  case JsArray(arr) => JsArray(arr.map(_.transform(picker).get))
  case v: JsValue =>
    v.transform(
      idChanger andThen (__ \ "children").json.update(picker) orElse
      idChanger
  ).get
}
Play Framework: Transform Result to Json

Play Framework: Transform Result to Json


By : user3526122
Date : March 29 2020, 07:55 AM
I wish this helpful for you how can I transform a result to Json in an reusable action? , Something like this?
code :
import play.api.libs.json._
import play.api.mvc._


object JsonAction extends Results {
  def apply[A, B](block: A => B)(implicit reads: Reads[A], writes: Writes[B]): Action[JsValue] =
    Action(BodyParsers.parse.json) { request =>
      val result = for {
        a <- Json.fromJson(request.body).asOpt
        b = block(a)
      } yield Ok(Json.toJson(b))
      result getOrElse InternalServerError(???)
    }
}
object JsonAction extends Results {
  def apply[A, B](block: A => (Option[(Status, B)]), 
                  noneStatus: Result = BadRequest("could not parse json"))
                 (implicit reads: Reads[A], writes: Writes[B]): Action[JsValue] =
    Action(BodyParsers.parse.json) { request =>
      val result = for {
        a <- Json.fromJson(request.body).asOpt
        (status, b) <- block(a)
      } yield status(Json.toJson(b))
      result getOrElse noneStatus
    }
}

object MathController {
  import JsonAction._
  def squareEquasion = JsonAction[Map[String, Double], Set[Double]] { map =>
    for {a <- map get "a"
         b <- map get "b"
         c <- map get "c"
         d = b * b - 4 * a * c} yield d match {
      case d if d < 0 => (InternalServerError, Set.empty[Double])
      case d if d == 0 => (Ok, Set(-b / 2 * a))
      case d if d > 0 => (Ok, Set(1, -1) map (q => (-b + q * math.sqrt(d)) / 2 * a))
    }
  }
}
import play.api.http.Writeable
import play.api.libs.json._
import play.api.mvc._

import scala.language.implicitConversions

object JsonAction {
  private object Res extends Results

  implicit def jsonWriteable[T](implicit writes: Writes[T]): Writeable[T] = {
    val jsonWriteable = implicitly[Writeable[JsValue]]
    def transform(obj: T) = jsonWriteable.transform(Json.toJson(obj))
    new Writeable[T](transform, jsonWriteable.contentType)
  }

  def apply[A, B](block: A => Option[Result],   noneStatus: Result = Res.BadRequest("could not parse json"))
                 (implicit reads: Reads[A], writes: Writes[B]): Action[JsValue] =
    Action(BodyParsers.parse.json) { request =>
      val result = for {
        a <- Json.fromJson(request.body).asOpt
        result <- block(a)
      } yield result
      result getOrElse noneStatus
    }
}

object MathController extends Results{
  import JsonAction._
  def squareEquasion = JsonAction[Map[String, Double], Set[Double]] { map =>
    for {a <- map get "a"
         b <- map get "b"
         c <- map get "c"
         d = b * b - 4 * a * c} yield d match {
      case d if d < 0 => InternalServerError("No answer")
      case d if d == 0 => Ok(Set(-b / 2 * a))
      case d if d > 0 => Ok(Set(1, -1) map (q => (-b + q * math.sqrt(d)) / 2 * a))
    }
  }
}
Related Posts Related Posts :
  • Assign generic method to variable in Scala
  • General Finite State Machine (Transducer) in Scala
  • What is the usage of a final var in Scala
  • Define Generic Types with String
  • Why there is a ClassCastException when isInstanceOf returns true on a scala type with wildcard parameter?
  • How to reaload scala application after code change using actors and sbt
  • akka non-blocking BoundedMailbox
  • Why are constructor parameters made into members for case classes?
  • Higher order tail recursive function needs to terminate early
  • How can I reusably filter based on type in Scala?
  • Why does Scala sbt update every time I start it from command prompt?
  • Recommended Scala io library
  • Thread-safely transforming a value in a mutable map
  • Why does chaining match expressions does not compile?
  • Ebean not persisting foreign keys
  • Difference between def m(p: T forSome {type T} and def m1(p:Any), is there any ? Explanation needed based on Scala Langu
  • macro does not find out enclosing vals
  • Spark : how to run spark file from spark shell
  • Flattening a list of lists to a set with exceptions in scala
  • flatMap implementation in Scala
  • Confused about a few lines code in a scala official document page
  • How to input parameters when running bash command with Scala
  • Location header is lost if max-redirects > 1
  • Controller Spec is using FakeApplication, but can't load test configuration
  • Scala code analyzer targets case variable names that are identical to the outer matched varables - "suspicous shado
  • Why does authorize directive execute after the code it's supposed to protect?
  • Scala. Checking if a Type is Comparable
  • Does having a private constructor on a value class negate the benefits of a value class?
  • Scala warning match may not be exhaustive
  • Pure not a member of objective Promise in PlayFramework
  • How to unmarshal POST params and JSON body in a single route?
  • Spark:How to use join method?
  • is client thread-safe in Twitter Finagle
  • Why is the method accepts only one argument?
  • Scala Play 2.3 Working with gCloud Storage - any libs to go async?
  • spray.io strange get/delete/detach directives behavior
  • SBT cannot resolve class declared in src/main/scala in a src/test/scala test class
  • Scala typeclass without function argument
  • Configuring actor behavior using typesafe Config and HOCON
  • Scalatra: Migrating Jersey Filters to Scalatra
  • Compilation error when using Scaldi
  • Scalac hanging in phase typer
  • how to have different source code when cross-compiling Scala with sbt? (changes in MurmurHash)
  • How to set different scalacOptions per Scala version when cross-compiling using Build.scala?
  • Possible Bug in JDBC?
  • Is there a Scala compiler flag to warn when tail recursion is applied without annotation?
  • scala case class put methods in companion object?
  • multiproject sbt doesn't generate file structure
  • Scala "multilevel" abstract class / abstract objects replacement
  • Scala, getting the type parameters of a KList as an HList
  • Why does Play refuse form reporting "Cannot resolve method apply with such signature: Missing arguments"?
  • How to split string with trailing empty strings in result?
  • Scala group by list of list and subtracts grouped values
  • Scala - Creating a function to produce Unary string or integer values
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org