Problem

如果字段是嵌套的,如何将字段添加到Json对象?

这与这个论坛类似:Adding field to a JSON using Circe

但不是:

{
  ExistingField: {},
  "Newfield" : {}
}

我的最终目标是:

{
  ExistingField: {},
  "A" : {
    "B" : {
      "C" : "myStringValue"
    }
  },
  "AA" : {
    "BB" : "myStringValue" 
  }
}

Tried

I have a list of nested fields of type String that I would like to iterate through and add.
Instead of them being nested, I just got:

{
  ExistingField: {},
  "A.B.C" : "myStringValue"
}

我的字段列表如下:

val listOfFields: List[String] = List("A.B.C", "AA.BB")

编辑:如果添加的字段是数组怎么办?例如:

{
  ExistingField: {},
  "A" : {
    "B" : {
      "C" : "myStringValue"
    }
  },
  "AA" : {
    "BB" : [
      {
        "CC": "myStringValue"
      },
      {
        "CC": "myStringValue"
      }
    ]
  }
}

推荐答案

循环函数使用模式匹配将子字段列表(来自分配器拆分字段)转换为嵌套Json,然后可以将其deepMerged转换为原始Json.foldLeft对最初列出的每个字段重复执行此操作.

import io.circe.generic.auto._
import io.circe.parser
import io.circe.syntax._
import io.circe.Json

val jsonStr = """{"Fieldalreadythere": {}}"""

val jsonParse = parser.parse(jsonStr)


val listOfFields: List[String] = List("A.B.C", "AA.BB")

val listOfSplitFields = listOfFields.map(_.split("\\.").toList)


def makeJson(list: List[String]): Json = {
  list match {
    case h :: Nil => Json.fromFields(List((h, Json.fromString("stringValue"))))
    case h :: t => Json.fromFields(List(h -> makeJson(t)))
    case Nil => Json.fromFields(Nil)
  }
}


val originalJson = jsonParse match {
       case Right(value) => value.asObject
       case Left(error) => throw error
    }


val updateJsons = listOfSplitFields.map(makeJson(_))
updateJsons.foldLeft(originalJson.asJson)(_.deepMerge(_))

结果(io.circe.Json型):

{
  "AA" : {
    "BB" : "stringValue"
  },
  "A" : {
    "B" : {
      "C" : "stringValue"
    }
  },
  "Fieldalreadythere" : {

  }
}

Json相关问答推荐

JoltChange:将输入数组的每个对象拆分为2个独立的对象,并将其放入输出数组中

JOLT拉平数组

使用相同的密钥值来命名Json并使用Jolt重命名密钥

JOLT转换过滤出特定值/对象

序列化从/到空值

Jolt-在数组列表中插入新的字段

如何在JSONata对象中迭代并向数组添加新字段?

展平多个数组以保持顺序

在 PowerShell 中通过 aws cli 创建 cloudwatch alert 时出现字符串解析错误

APIM 生成 JsonArray 到 EventHub

具有 (RegEx) 模式的 json-schema 中的枚举

使用 Groovy 将 XML 转换为 JSON

如何在linux中用jq过滤json数组?

序列化特定类型时如何使 JSON.Net 序列化程序调用 ToString()?

如何对使用转换器的 Grails 服务进行单元测试?

JSON RPC - 什么是id?

规范化 JSON 文件

在 JSON 反序列化期间没有为System.String类型定义无参数构造函数

如何通过 NSJSONSerialization 在 JSON 中包含空值?

将 json 转换为 C# 数组?