【问题标题】:Need to read Nested Json and parse it in two columns (Id, newId) using dataframe in scala需要读取嵌套 Json 并使用 scala 中的数据框将其解析为两列(Id,newId)
【发布时间】:2019-06-18 14:37:10
【问题描述】:

这里是需要分成两个特定列的示例数据

{ "tags": [ { "1": "NpProgressBarTag", "2": "userPath", "3": "screen", "4": 6, "12": 9, "13": "buttonName", "16": 0, "17": 10, "18": 5, "19": 6, "20": 1, "35": 1, "36": 1, "37": 4, "38": 0 },{ "1": "Progression", "2": "Path", "3": "Light", "4": 10, "12": 5, "13": "TagName" } ] }

输出应该是这样的

id    newid 
1     NpProgressBarTag
2     userpath
3     screen
4      6
12     9
13     buttonName
20      1

id     newId
1      Progression
2      path
3      Light
4      10
12     5
13     Tagname

谁能帮我解决这个问题。

【问题讨论】:

  • 表格格式的输出应该是 Id {所有左元素},newId{所有右元素}。谢谢
  • 您好,R,我不太确定您希望您的输出是什么样子。你想要两列名为 id 和 newId,然后每个数字一行?
  • @Jeremy 是的,我需要在两列 id 和 newId 中使用它。然后 id 列由 json 数据中的所有左侧元素组成,例如:1,2,3,4,12,13 和 newId 列由 json 数据中的所有右手元素组成,例如:[NpProgressBarTag, userpath, ...]跨度>
  • 还有一个问题:您是否希望 tags 数组中的每个元素都有一行,并且每个单元格包含一个数组?
  • @Jeremy 如果您可以为 Json 中的每个集合制作一个表格,那将不胜感激,或者您的方法对我有用

标签: json scala parsing nested multiple-columns


【解决方案1】:

您的数据有一件困难的事情,那就是它包含numbersstrings

我的解决方案使用play-json!

所以首先我创建了一个结构来将 Json 带入 Scala-Land:

  case class Tags(tags: Seq[Map[String, String]])

  object Tags {

    implicit val mapReads: Reads[Map[String, String]] = { jv: JsValue =>
      JsSuccess(jv.as[Map[String, JsValue]].map {
        case (k, v) =>
          k -> v.toString
      })
    }

    implicit val jsonReads: Reads[Tags] = Json.reads[Tags]


  }

如果您使用此阅读器implicit val jsonReads: Reads[Tags] = Json.reads[Tags] 创建case class

所有缺少的是地图阅读器。这会将通用 JsValue 更改为字符串。

用法:

json.validate[Tags] match {
    case JsSuccess(value, _) =>
      for{
        tags <- value.tags
        entry <- tags.toSeq
      } yield (entry._1, entry._2.toString)
    case err:JsError => // handleError
  }

这里基本上你将序列和地图展平。

结果是:List((12,9), (19,6), (4,6), (37,4), (13,"buttonName"),..

在这里你可以自己玩:https://scalafiddle.io/sf/kM6iBXF/2

【讨论】:

  • 感谢您的回复,这应该对我有帮助
  • 在编译时说 [not found value:object play] ---- not found: object play [error] import play.api.libs.json._ ----
  • 你添加了play-json依赖吗?
  • 是的。我想如果我没记错的话,这就是你所说的libraryDependencies += "com.typesafe.play" % "play-json_2.11" % "2.5.2"
  • 是的 - 如果你没有 play 项目(那么它包括在内) - 避免使用 scala 版本:"com.typesafe.play" %% "play-json" % "2.6.10"
猜你喜欢
  • 2016-07-12
  • 1970-01-01
  • 2021-01-02
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多