首页 > 解决方案 > Scala:根据内部值编辑/修改 json 字符串

问题描述

我有一个类似于以下结构的 json 字符串:

val json : String =
    {
       "identifier":{
          "id":"1234_567_910",
          "timestamp":"12:34:56",
       },
       "information":[
          {
             "fieldName":"test_name",
             "fieldId":"test_fieldId",
          }
       ]
    }

我想要做的是创建一个检查,验证“id”字段与结构“Int_Int_Int”是否匹配,如果不匹配,我想更改值以匹配这个预期的结构,但我想保留其余信息json字符串原样。

因此,如果我在 json 字符串中收到以下“id”字段,我想像这样更改它们:

"id":"1234_567_910" -> do nothing 
"id":"1234"         -> "id":"1234_0_0"
"id":"1234_567"     -> "id":"1234_567_0"
"id":"1234_???"     -> "id":"1234_0_0"
"id":"1234_??_???"  -> "id":"1234_0_0"
"id":"1234_foo"     -> "id":"1234_0_0"
"id":"1234_567_foo" -> "id":"1234_567_0"

例如:

如果我收到这样的json:

{
   "identifier":{
      "id":"1234",
      "timestamp":"12:34:56",
   },
   "information":[
      {
         "fieldName":"test_name",
         "fieldId":"test_fieldId",
      }
   ]
}

我想修改它,所以我最终得到一个像这样的 json:

{
   "identifier":{
      "id":"1234_0_0",
      "timestamp":"12:34:56",
   },
   "information":[
      {
         "fieldName":"test_name",
         "fieldId":"test_fieldId",
      }
   ]
}

在 Scala 中实现这种 json 修改的最有效/最干净的方法是什么?

标签: jsonscala

解决方案


下面是如何使用第戎库来完成的。

import com.github.pathikrit.dijon._

def normalize(id: String): String =
  id.count(_ == '_') match {
    case 0 => id + "_0_0"
    case 1 => id + "_0"
    case _ => id
  }

val json =
  json"""
    {
       "identifier":{
          "id":"1234",
          "timestamp":"12:34:56"
       },
       "information":[
          {
             "fieldName":"test_name",
             "fieldId":"test_fieldId"
          }
       ]
    }"""
json.identifier.id = json.identifier.id.asString.fold("0_0_0")(normalize)
println(pretty(json))

它应该打印:

{
  "identifier": {
    "id": "1234_0_0",
    "timestamp": "12:34:56"
  },
  "information": [
    {
      "fieldName": "test_name",
      "fieldId": "test_fieldId"
    }
  ]
}

推荐阅读