给定一个json数组和要在每个元素上使用的转换 - 如何在收集验证错误时将转换应用于所有元素?
scenario("pick attributes") {
Given("a json array and a transformation to be used on each element")
val jsonArray = Json.arr(
Json.obj("a" -> Json.obj("b" -> 1), "b" -> 2),
Json.obj("a" -> 2, "b" -> 4),
Json.obj("a" -> 3, "b" -> 6)
)
info(Json.stringify(jsonArray))
val elementTrans = (__ \ "b").json.update(__.read[Int] map { n => JsArray(Seq(JsNumber(n), JsNumber(n*2)))})
When("we do this (read a seq, map its elements to their transformed values, turn it into json again)")
//I lose the errors this way - what's a way to transform the whole thing and collect all errors?
val read = __.read[Seq[JsValue]] map { value =>
Json.toJson(
value.map { e =>
info("e: " + e)
e.transform(elementTrans).get
}
)
}
Then("the transformation took place on every single element")
jsonArray.validate(read).fold(
invalid = seq => fail(errorSequenceToString("invalid: ", seq)),
valid = a => info("valid: " + Json.stringify(a))
)
}
答案 0 :(得分:0)
您可以map
然后使用partition
将结果分为两类:失败的和失败的。