我有一个复杂的JSON列,其结构是:
故事{卡片:[{故事-元素:{.}{…}{}
故事元素的长度是可变的。我需要从故事元素数组中提取一个特定的JSON块。为此,我首先需要提取故事元素。
下面是我尝试过的代码,但是它出现了错误:
import org.json4s.{DefaultFormats, MappingException}
import org.json4s.jackson.JsonMethods._
import org.apache.spark.sql.functions._
def getJsonContent(jsonstring: String): (String) = {
implicit val formats = DefaultFormats
val parsedJson = parse(jsonstring)
val value1 = (parsedJson\"cards"\"story-elements").extract[String]
value1
}
val getJsonContentUDF = udf((jsonstring: String) =>
getJsonContent(jsonstring))
input.withColumn("cards",getJsonContentUDF(input("storyDataFrame")))发布于 2018-07-05 21:50:39
根据您提供的json,story-elements是一个json对象数组,但是您试图将数组提取为字符串((parsedJson\"cards"\"story-elements").extract[String])。
您可以创建表示故事的案例类(比如case class Story(description: String, pageUrl: String, ...)),然后用extract[List[Story]]或extract[Array[Story]]代替extract[String],如果您只需要从故事中提取一段数据(例如描述),那么您可以使用类似xpath的语法来获取它,然后提取List[String]。
https://stackoverflow.com/questions/51189507
复制相似问题