【问题标题】:Trying to read a json file into a Map[String,Object] in scala尝试将 json 文件读入 scala 中的 Map[String,Object]
【发布时间】:2020-05-22 14:16:13
【问题描述】:

我正在尝试将 json 配置文件读入我的 scala 项目。 json的格式如下:

{
  "parameters": [
    {
      "name": "testInteger",
      "type": "Integer",
      "value": "10"
    },
    {
      "name": "testString",
      "type": "String",
      "value": "yeah"
    }
  ]
}

我一直在用spark生成数据框

val df = spark.read.option("multiline","true").json(path)

我需要将 json 文件中的数据读取到具有键“名称”和指定类型值的 Map 中

预期输出:

Map: "testInteger" -> 10
     "testString" -> "yeah"

我是 scala 的新手,不确定从哪里开始,任何建议都将不胜感激。

(注:使用Java 8和intellij编写)

【问题讨论】:

  • 你能添加你的预期输出吗?
  • 转换成map后你想做什么。
  • 理想情况下想成为 "testInteger" -> 10, "testString" -> "yeah"
  • 我应该澄清一下,可能会有不止一个 Map 对象。在这种情况下,映射将被称为参数并将字符串(名称)映射到指定类型的值。我需要具有扩展功能以包含更多地图

标签: json scala apache-spark


【解决方案1】:

所以,这是你应该做的,

  1. 创建 SparkSession,
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{ArrayType, StructType}

val spark = SparkSession.builder().master("local[2]").getOrCreate()
import spark.implicits._
  1. 创建架构,
val schema = new StructType().add(
"parameters",ArrayType.apply(
      new StructType()
          .add("name", "string")
          .add("type", "string")
          .add("value", "string")
       ))
  1. 读取数据集,
 val df = spark.read
      .option("multiline", "true")
      .schema(schema)
      .json("/path/to/json")
      .select(explode(col("parameters")).alias("params"))

这将为您提供一个名为“params”的struct 列,其中包含nametypevalue 字段。这看起来像,

root
 |-- params: struct (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- type: string (nullable = true)
 |    |-- value: string (nullable = true)

注意:所有structmap 类型列都强制类型安全。因此模式不能允许在同一列中使用不同类型的值。因此,value 字段中的所有值都将转换为string。根据您的用例,您可以使用 udf 在运行时使用字段 type 进行转换。

【讨论】:

    猜你喜欢
    • 2015-08-14
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2013-05-24
    • 2014-01-29
    相关资源
    最近更新 更多