[英]how to parse the wiki infobox json with scala spark
我试图从Wiki API获取的json数据中获取数据
我能够完全打印出该模式
scala> data.printSchema
root
|-- batchcomplete: string (nullable = true)
|-- query: struct (nullable = true)
| |-- pages: struct (nullable = true)
| | |-- 28597189: struct (nullable = true)
| | | |-- ns: long (nullable = true)
| | | |-- pageid: long (nullable = true)
| | | |-- revisions: array (nullable = true)
| | | | |-- element: struct (containsNull = true)
| | | | | |-- *: string (nullable = true)
| | | | | |-- contentformat: string (nullable = true)
| | | | | |-- contentmodel: string (nullable = true)
| | | |-- title: string (nullable = true)
我想提取键“ *” |-- *: string (nullable = true)
请提出一个解决方案。
一个问题是
pages: struct (nullable = true)
| | |-- 28597189: struct (nullable = true)
每个标题唯一的编号28597189。
首先,我们需要解析json以动态获取密钥(28597189),然后使用它从spark数据帧中提取数据,如下所示
val keyName = dataFrame.selectExpr("query.pages.*").schema.fieldNames(0)
println(s"Key Name : $keyName")
这将为您动态提供密钥:
Key Name : 28597189
然后使用它来提取数据
var revDf = dataFrame.select(explode(dataFrame(s"query.pages.$keyName.revisions")).as("revision")).select("revision.*")
revDf.printSchema()
输出:
root
|-- *: string (nullable = true)
|-- contentformat: string (nullable = true)
|-- contentmodel: string (nullable = true)
我们将使用某些键名(例如star_column
重命名*
列
revDf = revDf.withColumnRenamed("*", "star_column")
revDf.printSchema()
输出:
root
|-- star_column: string (nullable = true)
|-- contentformat: string (nullable = true)
|-- contentmodel: string (nullable = true)
一旦有了最终的数据框,我们将称其为show
revDf.show()
输出:
+--------------------+-------------+------------+
| star_column|contentformat|contentmodel|
+--------------------+-------------+------------+
|{{EngvarB|date=Se...| text/x-wiki| wikitext|
+--------------------+-------------+------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.