首页 > 解决方案 > 在 Python 中使用包含在 spark.read() 的 json 文件中的模式

问题描述

问题:

  1. 我的模式转换为 json 是否正确?
  2. 如何传递 json 文件为 spark.read() 提供模式

我将以下架构硬编码到 python 脚本中,这非常适合我的代码:

schema1 = StructType([
            StructField("computer_name", StringType()),
            StructField("owner_id", StringType())])

我想将模式从 json 文件中的脚本中移出,所以我进行了以下转换:

{"StructType":[
    {"fields":[
    {"metadata":{},"name":"computer_name","nullable":true,"type":"string"},
    {"metadata":{},"name":"owner_id","nullable":true,"type":"string"},
    "type":"struct"}
    ]
}

我想读取一个文件并使用 json 文件提供我自己的架构:

df=spark.read.option("header", "true").schema(schema_json_file).load(file_names)

这将引发以下错误:

ERROR: schema should be StructType or string

标签: pythonjsonpysparkschema

解决方案


以下是我解决问题的方法:

.json 文件:

{"fields":[
{"metadata":{},"name":"computer_name","nullable":true,"type":"string"},
{"metadata":{},"name":"owner_id","nullable":true,"type":"string"}],
"type":"struct"}

Python代码:

schema_file = s3.Object("bucket_name",  "prefix")
schema_file = json.loads(schema_file.get()['Body'].read().decode('utf-8'))
custom_schema = StructType.fromJson(schema_file)
df=spark.read.option("header", "true").schema(custom_schema).load(file_names)

就我而言,带有架构的 json 文件位于 S3 位置。


推荐阅读