gpt4 book ai didi

scala - JArray 中的 TransformField 与 json4s

转载 作者:行者123 更新时间:2023-12-05 05:26:08 32 4
gpt4 key购买 nike

我正在尝试 Scala,尤其是 json4s lib 以便操作一些 json。我很难理解 Scala 和 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))))))

我现在面临的问题是:

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

例如(我知道这在 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
))))))

关于scala - JArray 中的 TransformField 与 json4s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27937828/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com