在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,"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)))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...