如何将JSON读为映射[字符串,字符串]?

发布于 2025-02-11 07:24:33 字数 571 浏览 1 评论 0原文

解析JSON映射[String,String]时,我会遇到问题。这个想法是将嵌套的对象解析为“键”。

我们可以格式化此输入JSON:

{
   "key-1":{
       "sub-key-1-1":{
           "sub-key-1-1-1":"value111"
        },
        "sub-key-1-2":{
           "sub-key-1-2-1":"value121"
        }
    },
    "key-2":{
       "sub-key-2-1":{
           "sub-key-2-1-1":"value211"
       }
    }
}

以将其作为映射[String,String]:

("key-1.sub-key-1-1.sub-key-1-1-1"->"value111", 
"key-1.sub-key-1-2.sub-key-1-2-1"->"value121",
"key-2.sub-key-2-1.sub-key-2-1-1"->"value211")

I got the problem when parsing JSON to Map[String, String]. The idea is to parse the nested object to a key separate by "."

Can we format this input JSON:

{
   "key-1":{
       "sub-key-1-1":{
           "sub-key-1-1-1":"value111"
        },
        "sub-key-1-2":{
           "sub-key-1-2-1":"value121"
        }
    },
    "key-2":{
       "sub-key-2-1":{
           "sub-key-2-1-1":"value211"
       }
    }
}

to this result as Map[String,String]:

("key-1.sub-key-1-1.sub-key-1-1-1"->"value111", 
"key-1.sub-key-1-2.sub-key-1-2-1"->"value121",
"key-2.sub-key-2-1.sub-key-2-1-1"->"value211")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泛滥成性 2025-02-18 07:24:33

您可以这样考虑,如果JSValue是JSOBJECT,则需要提取键值并将其附加到函数的当前状态,如果是其他功能,您只需将它们添加到函数的状态中,然后退还它们。递归思考:

import play.api.libs.json._

def iterateJson(js: JsValue, currentKey: Option[String] = None, acc: Map[String, String] = Map.empty): Map[String, String] = {
    js match {
      case obj: JsObject =>
        obj.keys.foldLeft(acc) {
          case (updatingMap, newKey) =>
            iterateJson(obj.value(newKey), currentKey.map(k => s"$k.$newKey") orElse Some(newKey), updatingMap)
        }
      case other =>
        (currentKey map (key => acc.updated(key, other.toString()))) getOrElse acc
    }
  }

请参阅在

You can think about it this way, if the JsValue is a JsObject, you need to extract the key values and append them to the current state of your function, if it's anything else, you can just add them to the state of your function, and then return them. Thinking recursively:

import play.api.libs.json._

def iterateJson(js: JsValue, currentKey: Option[String] = None, acc: Map[String, String] = Map.empty): Map[String, String] = {
    js match {
      case obj: JsObject =>
        obj.keys.foldLeft(acc) {
          case (updatingMap, newKey) =>
            iterateJson(obj.value(newKey), currentKey.map(k => s"$k.$newKey") orElse Some(newKey), updatingMap)
        }
      case other =>
        (currentKey map (key => acc.updated(key, other.toString()))) getOrElse acc
    }
  }

See the code running on scastie

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文