开发者社区> 问答> 正文

Spark如何从一行中仅提取Json数据

我有一堆文件,每行代码如下:

some random non json stuff here {"timestmap":21212121, "name":"John"}
我无法将这些文件作为json读取,因为Json数据之前存在随机的东西。

清除随机内容以便能够将Json数据加载到具有适当列的DF中的最佳方法是什么?

最终目标是使最终DF只包含时间戳在特定日期之间的数据。

展开
收起
社区小助手 2018-12-05 14:47:25 3641 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    此解决方案使用

    instr找到JSON curly braces的出现{and}
    substr 获取JSON curly braces之间的子串(JSON文本)
    然后它使用from_json定义预期JSON结构的模式。

    from pyspark.sql.functions import from_json, instr
    from pyspark.sql.types import *

    Expected JSON schema

    schema = StructType([StructField("timestmap", TimestampType()),

                     StructField("name", StringType())])

    Filtering and parsing

    parsed = df.select(from_json(

                df.value.substr(instr(df.value, '{'), instr(df.value, '}')), 
                schema).alias("json"))
    

    Don't know if it's possible to do it in one step ...

    parsed = parsed.select(F.col("json.timestmap").alias("timestmap"),

                       F.col("json.name").alias("name"))
    

    parsed.printSchema()
    parsed.show()
    结果是

    root
    |-- timestmap: timestamp (nullable = true)
    |-- name: string (nullable = true)

    timestmap name
    1970-09-03 12:15:21 John
    1970-09-03 12:15:22 Doe

    示例文本文件random.txt是

    some random non json stuff here {"timestmap":21212121, "name":"John"}
    some other random non json stuff here {"timestmap":21212122, "name":"Doe"}

    2019-07-17 23:18:23
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Hybrid Cloud and Apache Spark 立即下载
Scalable Deep Learning on Spark 立即下载
Comparison of Spark SQL with Hive 立即下载