我是新手。我试图使用 SparkSQL 在 spark 中解析下面提到的 JSON 文件,但它没有用。有人可以帮我解决这个问题吗。
输入JSON:
[{"num":"1234","Projections":[{"Transactions":[{"14:45":0,"15:00":0}]}]}]
预期输出:
1234 14:45 0\n
1234 15:00 0
我试过下面的代码,但是没有用
val sqlContext = new SQLContext(sc)
val df = sqlContext.read.json("hdfs:/user/aswin/test.json").toDF();
val sql_output = sqlContext.sql("SELECT num, Projections.Transactions FROM df group by Projections.TotalTransactions ")
sql_output.collect.foreach(println)
输出:
[01532,WrappedArray(WrappedArray([0,0]))]
最佳答案
Spark 将您的 {"14:45":0,"15:00":0}
映射识别为结构,因此读取数据的唯一方法可能是手动指定模式:
>>> from pyspark.sql.types import *
>>> schema = StructType([StructField('num', StringType()), StructField('Projections', ArrayType(StructType([StructField('Transactions', ArrayType(MapType(StringType(), IntegerType())))])))])
然后你可以查询这个临时表,使用多重分解得到结果:
>>> sqlContext.read.json('sample.json', schema=schema).registerTempTable('df')
>>> sqlContext.sql("select num, explode(col) from (select explode(col.Transactions), num from (select explode(Projections), num from df))").show()
+----+-----+-----+
| num| key|value|
+----+-----+-----+
|1234|14:45| 0|
|1234|15:00| 0|
+----+-----+-----+
关于json - 使用 Spark 解析 JSON 文件并提取键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42017972/