玩法2.3:如何统计json个子节点?

Play 2.3: How to count json child nodes?

我有这个json:

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

如何统计"errors"节点下的子节点?

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

Object.keys(a.errors).length;

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

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)