在 spark 中解析 json

Parsing json in spark

我在 spark 作业中使用 json scala 库从本地驱动器解析 json :

val requestJson=JSON.parseFull(Source.fromFile("c:/data/request.json").mkString)
    val mainJson=requestJson.get.asInstanceOf[Map[String,Any]].get("Request").get.asInstanceOf[Map[String,Any]]
    val currency=mainJson.get("currency").get.asInstanceOf[String]

但是当我尝试通过指向 hdfs 文件位置来使用相同的解析器时它不起作用:

val requestJson=JSON.parseFull(Source.fromFile("hdfs://url/user/request.json").mkString)

并给我一个错误:

java.io.FileNotFoundException: hdfs:/localhost/user/request.json (No such file or directory)
  at java.io.FileInputStream.open0(Native Method)
  at java.io.FileInputStream.open(FileInputStream.java:195)
  at java.io.FileInputStream.<init>(FileInputStream.java:138)
  at scala.io.Source$.fromFile(Source.scala:91)
  at scala.io.Source$.fromFile(Source.scala:76)
  at scala.io.Source$.fromFile(Source.scala:54)
  ... 128 elided

如何使用 Json.parseFull 库从 hdfs 文件位置获取数据?

谢谢

Spark 确实内置了对 JSON 文档解析的支持,这将在 spark-sql_${scala.version} jar 中可用。

在 Spark 2.0+ 中:

import org.apache.spark.sql.SparkSession 

val spark: SparkSession = SparkSession.builder.master("local").getOrCreate

val df = spark.read.format("json").json("json/file/location/in/hdfs")

df.show()

使用 df 对象,您可以对其执行所有支持的 SQL 操作,并且它的 数据处理将分布 在节点之间,而 requestJson 只会在单机计算。

Maven 依赖关系

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.0.0</version>
</dependency>

Edit: (as per comment to read file from hdfs)

val hdfs = org.apache.hadoop.fs.FileSystem.get(
             new java.net.URI("hdfs://ITS-Hadoop10:9000/"), 
             new org.apache.hadoop.conf.Configuration()
           )
val path=new Path("/user/zhc/"+x+"/")
val t=hdfs.listStatus(path)
val in =hdfs.open(t(0).getPath)
val reader = new BufferedReader(new InputStreamReader(in))
var l=reader.readLine()

code credits: from another SO question

Maven dependencies:

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-hdfs</artifactId>
    <version>2.7.2</version> <!-- you can change this as per your hadoop version -->
</dependency>

在 spark 2.0 中更容易

val df = spark.read.json("json/file/location/in/hdfs")
df.show()

可以在 Spark 中使用以下命令从 HDFS 读取文件: val jsonText = sc.textFile("hdfs://url/user/request.json").collect.mkString("\n")