json - 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 修改的最有效/最干净的方法是什么?
解决方案
下面是如何使用第戎库来完成的。
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"
}
]
}
推荐阅读
- django-models - 如何在 django 管理模型中添加单选按钮
- javascript - 旋转轮子并在 EaselJs 中的特定点停止
- python - 我在哪里可以找到关于 seaborn 中的联合绘图函数或 Python 中的 matplotlib 中的此参数“joint_kws”的详细定义?
- vert.x - Vertx 实例变量在尝试从其方法访问时为空
- gradle - 如何使用 gradle 构建 WAR 文件?
- swift - Swift - 尝试打开一个我已经删除的桥接头
- c# - C# 在发送带有 **Plain-text** 和 **Html** 内容的电子邮件时遇到问题
- javascript - 清洁受污染的帆布
- php - 从另一个 zip 文件中的 zip 文件读取文件名
- laravel - Laravel Nova:属于许多人。根据条件在详细信息页面上显示列表(来自数据库)