JArray 中的 TransformField 与 json4s

TransformField in JArray with json4s

我正在尝试 Scala,特别是 json4s lib in order to manipulate some json. I'm having a hard time with the syntax of both Scala and json4s,我想问问你们。

我有这个 json,我需要更新其中的一些字段,然后完整地发回服务。 json 看起来像这样:

{
    "id": "6804",
    "signatories": [
        {
            "id": "12125",
            "fields": [
                {
                    "type": "standard",
                    "name": "fstname",
                    "value": "John"
                },
                {
                    "type": "standard",
                    "name": "sndname",
                    "value": "Doe"
                },
                {
                    "type": "standard",
                    "name": "email",
                    "value": "john.doe@somwhere.com"
                },
                {
                    "type": "standard",
                    "name": "sigco",
                    "value": "Company"
                }
            ]
        }
    ]
}

我正在使用 json4s 将其解析为 JArray,如下所示:

import org.json4s._
import org.json4s.native.JsonMethods._

val data = parse(json)
val fields = (data \ "signatories" \ "fields")

这给了我一个包含所有字段的 JArray:(非常抱歉格式化)

JArray(List(JObject(List((type,JString(standard)), (name,JString(fstname)), (value,JString(John)))), JObject(List((type,JString(standard)), (name,JString(sndname)), (value,JString(Doe)))), JObject(List((type,JString(standard)), (name,JString(email)), (value,JString(john.doe@somwhere.com)))), JObject(List((type,JString(standard)), (name,JString(sigco)), (value,JString(Company))))))

我现在面临的问题是:

如何找到每个字段 属性 "name",并将其更改(转换)为新值?

例如(我知道这在 Scala 中很可能不是这样工作的,但你会明白的)

foreach(field in fields) {
     if(field.name == 'fstname') {
          field.value = "Bruce"
     }
}

你可以试试

val a = JArray(List(JObject(....))) // Same as your JArray<pre><code>   

a.transform {
 // Each JArray is made of objects. Find fields in the object with key as name and value as fstname
case obj: JObject => obj.findField(_.equals(JField("name", JString("fstname")))) match {
  case None => obj //Didn't find the field. Return the same object back to the array
  // Found the field. Change the value
  case Some(x) => obj.transformField { case JField(k, v) if k == "value" => JField(k, JString("Bruce")) } 
}
}    

结果 -


res0: org.json4s.JValue = JArray(List(JObject(List((typ,JString(standard)), <strong>(name,JString(fstname)), (value,JString(Bruce))))</strong>, JObject(List((typ,JString(standard)), (name,JString(sndname)), (
ring(Doe)))), JObject(List((typ,JString(standard)), (name,JString(email)), (value,JString(john.doe@somwhere.com)))), JObject(List((typ,JString(standard)), (name,JString(sigco)), (value,JStrin
)))))) </pre>

简短的解决方案:

val modified = data transformField {
  case JField("name", JString("fstname")) => ("name", "Bruce")
}

查看 github 中的更多示例。