播放2.3:如何计算json子节点?

时间:2015-02-25 05:40:50

标签: json scala playframework playframework-json

我有这个json:

{
  "errors": {
    "password": [
      "This field is required"
    ],
    "email": [
      "This field is required"
    ]
  }
}

如何计算"错误"下的子节点?节点

2 个答案:

答案 0 :(得分:5)

一种方法,你可以这样做:

import play.api.libs.json.{JsObject, Json}

val errors = """{"errors":{"password":["This field is required"],"email":["This field is required"]}}"""
val errorsCount = Json.parse(errors).
    asOpt[JsObject].
    flatMap(json => (json \ "errors").asOpt[JsObject]).
    map(json => json.fields.size).getOrElse(0)

答案 1 :(得分:0)

var a = {
    "errors": {
        "password": [
            "This field is required"
        ],
        "email": [
            "This field is required"
        ]
    }
};

Object.keys(a.errors).length;