代码之家  ›  专栏  ›  技术社区  ›  NamrataK

从spark中Json内的数组中提取Json

  •  1
  • NamrataK  · 技术社区  · 8 年前

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

    卡片:[{故事元素:[{…}{…}{…}{…}}]}

    故事元素的长度是可变的。我需要从story元素数组中提取一个特定的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")))
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Eugene Platonov    8 年前

    根据你提供的json, story-elements (parsedJson\"cards"\"story-elements").extract[String]

    你可以创建一个表示故事的case类(比如 case class Story(description: String, pageUrl: String, ...) extract[String] ,试试看 extract[List[Story]] extract[Array[Story]] 如果您只需要story中的一段数据(例如description),那么您可以使用类似xpath的语法来获取这些数据,然后进行提取 List[String]

    推荐文章