简体   繁体   English

使用 Pyspark 如何读取 JSON 文件并创建模式

[英]Using Pyspark how to read JSON file and create schema

I have a JSON file as below format.我有一个 JSON 文件,格式如下。 How to read it and create schema for this using PYSPARK function-如何使用 PYSPARK 函数读取它并为此创建模式 -

{
        "Entry": {
                "DataType": "Integer",
                "Length": "7",
                "Required": "True",
                "Description": "Enrty"
        },
        "Per": {
                "DataType": "String",
                "Length": "2",
                "Required": "True",
                "Description": "Per"
        }
}

You can do the following to get the schema from the json file you have您可以执行以下操作以从您拥有的json文件中获取schema

from pyspark.sql import types as t
def getDataType(DataType):
    if DataType == 'Float':
        return t.FloatType()
    elif DataType == 'Integer':
        return t.IntegerType()
    elif DataType == 'Date':
        return t.DateType()
    elif DataType == 'Double':
        return t.DoubleType()
    else:
        return t.StringType()

def getNullable(Required):
    if Required == 'True':
        return True
    else:
        return False

df = spark.read.option('multiline', True).json('path to json file')
schema = t.StructType([t.StructField(x['Description'], getDataType(x['DataType']), getNullable(x['Required'])) for x in df.rdd.first()])

so the schema should be所以schema应该是

StructType(List(StructField(Enrty,IntegerType,true),StructField(Per,StringType,true)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 读取 pyspark 中的 JSON 文件,在 python 中创建模式结构类型 - Read JSON file in pyspark to create schema struct type in python 使用 pyspark 中的 json 文件中的模式读取固定宽度文件 - Read fixed width file using schema from json file in pyspark pyspark 如何为数组和结构创建模式以读取 json - pyspark how to create schema for array and struct to read json 如何使用推断模式读取列名中带点的 JSON 文件(Spark/Pyspark)? - How to read JSON file (Spark/Pyspark) with dots in column names using inferred schema? 如何使用 pyspark 将数据帧转换为分配特定模式的 JSON 文件? - How to convert a dataframe into a JSON file assigning a specific schema using pyspark? 使用 PySpark 将 JSON 文件读取为 Pyspark 数据帧? - Read JSON file as Pyspark Dataframe using PySpark? 如何在 PySpark 中为嵌套的 JSON 列创建模式? - How to create schema for nested JSON column in PySpark? 使用 pyspark 和预定义的结构模式读取嵌套 JSON 时,如何将缺失的列添加为 null - How can missing columns be added as null while read a nested JSON using pyspark and a predefined struct schema 如何读取文本文件并使用 PySpark 应用架构? - How do I read a text file & apply a schema with PySpark? PySPark:如何从pyspark中的变量创建JSON和CSV文件? - PySPark: How to create JSON and CSV file from a variable in pyspark?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM