从 json 模式表示创建 spark 数据帧模式 [英] Create spark dataframe schema from json schema representation

查看:31
本文介绍了从 json 模式表示创建 spark 数据帧模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将数据帧模式序列化为 json 并稍后反序列化?

Is there a way to serialize a dataframe schema to json and deserialize it later on?

用例很简单:我有一个 json 配置文件,其中包含我需要读取的数据帧的架构.我希望能够从现有模式(在数据帧中)创建默认配置,并且我希望能够通过从 json 字符串中读取来生成稍后使用的相关模式.

The use case is simple: I have a json configuration file which contains the schema for dataframes I need to read. I want to be able to create the default configuration from an existing schema (in a dataframe) and I want to be able to generate the relevant schema to be used later on by reading it from the json string.

推荐答案

为此有两个步骤:从现有数据帧创建 json 和从之前保存的 json 字符串创建架构.

There are two steps for this: Creating the json from an existing dataframe and creating the schema from the previously saved json string.

从现有数据帧创建字符串

    val schema = df.schema
    val jsonString = schema.json

从 json 创建架构

    import org.apache.spark.sql.types.{DataType, StructType}
    val newSchema = DataType.fromJson(jsonString).asInstanceOf[StructType]

这篇关于从 json 模式表示创建 spark 数据帧模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆