简体   繁体   English

使用io.circe转换JSON值

[英]Translating JSON values using io.circe

I have a function in scala that translates a value and produces a string. 我在scala中有一个函数,可以转换值并生成字符串。

strOut = translate(strIn)

Suppose the following JSON object: 假设以下JSON对象:

{
  "id": "c730433b-082c-4984-3d56-855c243265f0",
  "standard": "stda",
  "timestamp": "tsx000",
  "stdparms" : {
    "stdparam1": "a",
    "stdparam2": "b"
  }
}

and the following mapping provided by the translation function: 以及转换功能提供的以下映射:

"stda" -> "stdb"
"tsx000" -> "tsy000"
"a" -> "f"
"b" -> "g"

What is the best way to translate the whole JSON object using the translate function? 使用translate函数转换整个JSON对象的最佳方法是什么? My goal is to obtain the following result: 我的目标是获得以下结果:

{
  "id": "c730433b-082c-4984-3d56-855c243265f0",
  "standard": "stdb",
  "timestamp": "tsy000",
  "stdparms" : {
    "stdparam1": "f",
    "stdparam2": "g"
  }
}

I must use the io.circe library due to project related matters. 由于项目相关的原因,我必须使用io.circe库。

If you know beforehand which fields you want to translate, or what translations apply to that field, you can use Cursors to traverse the JSON tree. 如果您事先知道要翻译哪些字段,或者该字段适用什么翻译,则可以使用Cursors遍历JSON树。 Or if the fields themselves are fixed (you always know what fields to expect) Optics may require less code. 或者,如果字段本身是固定的(您总是知道需要哪些字段), 光学可能需要更少的代码。

When you get to the right leaf, you apply the translation. 当您到达正确的位置时,可以应用翻译。

However, when you don't know what could apply when/where it might be easier to find/replace using string methods. 但是,当您不知道什么时候/什么地方适用时,使用字符串方法可能更容易查找/替换。

Note that the JSON you provided as an example is not valid JSON by the way. 请注意,您作为示例提供的JSON并不是有效的JSON。

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

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