简体   繁体   English

在argonaut中转换JSON字段名称

[英]Converting JSON field names in argonaut

I'm writing a library to convert JSON responses from an API for backwards compatibility reasons. 我正在编写一个库来转换来自API的JSON响应,以实现向后兼容性。 And what I need to do is take in arbitrary JSON, and change certain field names. 我需要做的是接受任意JSON,并更改某些字段名称。 I'm using scala and argonaut, but I don't see any way in the docs or examples of changing the FIELD names, only the values. 我正在使用scala和argonaut,但我没有看到更改FIELD名称的文档或示例中的任何方法,只有值。

I don't know of a particularly nice way to do this, but it's not too awful to write a helper that will replace a field in an object and then use that in a cursor with withObject : 我不知道有什么特别好的方法可以做到这一点,但编写一个帮助器来替换对象中的字段然后在带有withObject的游标中使用它并不是太糟糕:

def renameField(before: JsonField, after: JsonField)(obj: JsonObject) =
  obj(before).map(v => (obj - before) + (after, v)).getOrElse(obj)

Parse.parseOption("""{ "a": { "b": { "c": 1 } } }""").flatMap { json =>
  (json.hcursor --\ "a").withFocus(_.withObject(renameField("b", "z"))).undo
}

This will return Some({"a":{"z":{"c":1}}}) as expected. 这将按预期返回Some({"a":{"z":{"c":1}}})

I ended up folding over the object I need to convert and adding to a map, and then creating a new json object. 我最终折叠了我需要转换的对象并添加到地图,然后创建一个新的json对象。

val conversionMap = Map("a" -> "b")

Json(
  j.objectOrEmpty.toMap.foldLeft(Map.empty[JsonField, Json]) {
    case (acc, (key, value)) =>
      acc.updated(conversionMap.getOrElse(key, key), j.fieldOrNull(key))
  }.toSeq: _*
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM