遍历 JSON 并在 Scala 中添加新字段

问题描述 投票:0回答:1

我有一个 JSON 结构,如下所示:

{
  "A": {
    "NestedArray": [
      {
        "AlreadyHere2": "x"
      },
      {
        "AlreadyHere2": "x"
      },
      {
        "AlreadyHere2": "x"
      }
    ]
  }
}

我需要将具有相同 CONSTANT 值的新 Json 字段添加到现有 json 文档的特定部分,使其变为:

{
  "A": {
    "A_1": "CONSTANT",
    "A_2": "CONSTANT",
    "NestedArray": [
      {
        "AlreadyHere2": "x",
        "arrayValue": "CONSTANT"
      },
      {
        "AlreadyHere2": "x",
        "arrayValue": "CONSTANT"
      },
      {
        "AlreadyHere2": "x",
        "arrayValue": "CONSTANT"
      }
    ]
  }
}

注意:对于数组,请为每个元素添加 CONSTANT。

我有一个特定 json 路径的列表,可用作“遍历指南”,将来可能会添加更多值,因此我的实现无法根据现有的 json 结构进行定制。即:

val list = List("A.A_1", "A.A_2", "A.NestedArray.arrayValue")

我看到有这个用于递归修改JSON:https://circe.github.io/circe/optics.html#recursively-modifying-json

但我不确定如何处理添加到特定的 new 字段和数组中。任何帮助将不胜感激,谢谢!

json scala circe-optics
1个回答
0
投票

使用案例类,您可以解码编码

case class OuterClass(A: ClassA)

case class ClassA(
                   NestedArray: Seq[ClassB]
                 )

case class ClassB(
                   AlreadyHere2: String
                 )

case class OuterClass1(A: ClassA1)
object OuterClass1 {
  def fromOuterClass(outer: OuterClass, A_1: String, A_2: String, arrayValue: String): OuterClass1 =
    OuterClass1(ClassA1.fromClassA(A_1, A_2, outer.A, arrayValue))
}

case class ClassA1(
                    A_1: String,
                    A_2: String,
                    NestedArray: Seq[ClassB1]
                  )
object ClassA1 {
  def fromClassA(A_1: String, A_2: String, a: ClassA, arrayValue: String): ClassA1 =
    ClassA1(A_1, A_2, a.NestedArray.map(ClassB1.fromClassB(_, arrayValue)))
}

case class ClassB1(
                   AlreadyHere2: String,
                   arrayValue: String,
                  )
object ClassB1 {
  def fromClassB(b: ClassB, arrayValue: String): ClassB1 = ClassB1(b.AlreadyHere2, arrayValue)
}

def transform(jsonStr: String): String = {
  val outer = decode[OuterClass](jsonStr).toOption.get
  val outer1 = OuterClass1.fromOuterClass(outer, "CONSTANT", "CONSTANT", "CONSTANT")
  outer1.asJson.spaces2
}

val str =
  """{
    |    "A": {
    |      "NestedArray": [
    |        {
    |          "AlreadyHere2": "x"
    |        },
    |        {
    |          "AlreadyHere2": "x"
    |        },
    |        {
    |          "AlreadyHere2": "x"
    |        }
    |      ]
    |    }
    |}""".stripMargin

transform(str)

//{
//  "A" : {
//    "A_1" : "CONSTANT",
//    "A_2" : "CONSTANT",
//    "NestedArray" : [
//      {
//        "AlreadyHere2" : "x",
//        "arrayValue" : "CONSTANT"
//      },
//      {
//        "AlreadyHere2" : "x",
//        "arrayValue" : "CONSTANT"
//      },
//      {
//        "AlreadyHere2" : "x",
//        "arrayValue" : "CONSTANT"
//      }
//    ]
//  }
//}
© www.soinside.com 2019 - 2024. All rights reserved.