在遍历 JSON Circe Scala 中的所有节点后有条件地添加字段

add field conditionally after traversing all nodes in JSON Circe Scala

假设我有一个复杂的 JSON:

{
  "type": "object",
  "properties": {
    "first_name": { "type": "string" },
    "last_name": { "type": "string" },
    "birthday": { "type": "string", "format": "date" },
    "address": {
      "type": "object",
      "properties": {
        "street_address": { "type": "string" },
        "city": { "type": "string" },
        "state": { "type": "string" },
        "country": { "type" : "string" }
      }
    }
  }
}

我想将字段 additionalProperties: false 添加到具有 type:object 的所有 json 个对象 在上面的例子中,输出 json 看起来像:

{
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "first_name": { "type": "string" },
    "last_name": { "type": "string" },
    "birthday": { "type": "string", "format": "date" },
    "address": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "street_address": { "type": "string" },
        "city": { "type": "string" },
        "state": { "type": "string" },
        "country": { "type" : "string" }
      }
    }
  }
}

这是我目前拥有的:

val circeJson: io.circe.Json = parser.parse(json).getOrElse(io.circe.Json.Null)
    val updatedJson = transform(circeJson)

def transform(js: io.circe.Json): io.circe.Json =
    js
      .mapArray(_.map(transform))
      .mapObject(obj => obj.+:("additionalProperties", io.circe.Json.fromBoolean(false)))

出于某种原因,它正在运行并仅为根级对象添加字段。

以下有效:

 def transformJson(js: io.circe.Json, transformation: JsonObject => JsonObject): io.circe.Json =
    js
      .mapArray(_.map(transformJson(_, transformation)))
      .mapObject(obj => transformation(obj).mapValues(obj => transformJson(obj, transformation)))

 val circeJson: io.circe.Json = parser.parse(json).getOrElse(io.circe.Json.Null)
 val updatedJson =
      transformJson(circeJson, obj => obj.+:("additionalProperties", io.circe.Json.fromBoolean(false)))