【问题标题】:Extract a Json from an array inside a json in spark从spark中的json中的数组中提取Json
【发布时间】:2018-07-05 10:53:38
【问题描述】:

我有一个复杂的 JSON 列,其结构是:

故事{ 卡片:[{story-elements: [{...}{...}{...}}]}

故事元素的长度是可变的。我需要从故事元素数组中提取一个特定的 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")))

【问题讨论】:

  • 你能发布整个 JSON 吗?
  • {故事:{卡片:[{故事元素:[{描述:“”,页面网址:“/story/03d952fb-83f9-468e-a02c-fe6e2431fa6c/element/fa52a7d9-1d02 -4214-b7ab-e86c8c635403”,类型:“文本”,family-id:“22f2d777-d51e-435a-a4d8-ba47f0b9e257”,标题:“”,id:“fa52a7d9-1d02-4214-b7ab-e86c8c635403”,元数据: { }, subtype: null, text: "

    两位卡纳达语演员 Raghava Uday 和 Anil 在星期一不幸去世

    " } ]} ] }
  • 也提出质疑
  • 链接没有作用

标签: json scala apache-spark apache-spark-sql


【解决方案1】:

根据您提供的 json,story-elements 是一个 json 对象数组,但您试图将数组提取为字符串 ((parsedJson\"cards"\"story-elements").extract[String])。

您可以创建代表故事的案例类(如case class Story(description: String, pageUrl: String, ...)),然后代替extract[String],尝试extract[List[Story]]extract[Array[Story]] 如果您只需要故事中的一条数据(例如描述),那么您可以使用类似 xpath 的语法来获取它,然后提取 List[String]

【讨论】:

    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2014-03-02
    • 2019-04-21
    相关资源
    最近更新 更多