Moritz
Moritz

Reputation: 565

Pyspark: create a schema from JSON file

I am working with data from very long, nested JSON files. Problem is, that the structure of these files is not always the same as some of them miss columns others have. I want to create a custom schema from an empty JSON file that contains all columns. If I later read JSON files into this pre-defined schema, the non-existing columns will be filled with null values (thats at least the plan). What I did so far:

  1. loading a test JSON (that does not contain all columns that can be expected) into a dataframe
  2. writing its schema into a JSON file
  3. Opening this JSON file in a text-editor and adding the missing columns manually

Next thing I want to do is creating a new schema by reading the JSON file into my code, but I struggle with the synthax. Can I read the schema directly from the file itself? I have tried

schemaFromJson = StructType.fromJson(json.loads('filepath/spark-schema.json'))

but it gives me TypeError: init() missing 2 required positional arguments: 'doc' and 'pos'

Any idea whats wrong about my current code? Thanks a lot

edit: I came across this link sparkbyexamples.com/pyspark/pyspark-structtype-and-structfield . Chapter 7 pretty much describes the problem I am having. I just dont understand how I can parse the json file I manually enhanced to schemaFromJson = StructType.fromJson(json.loads(schema.json)).

When I do:

jsonDF = spark.read.json(filesToLoad)
schema = jsonDF.schema.json()
schemaNew = StructType.fromJson(json.loads(schema))
jsonDF2 = spark.read.schema(schemaNew).json(filesToLoad)

The code runs through, but its obviously not useful because jsonDF and jsonDF2 do have the same content/schema. What I want to achieve, is adding some columns to 'schema' which will then be reflected in 'schemaNew'.

Upvotes: 5

Views: 41137

Answers (3)

Preetish ranjan Barik
Preetish ranjan Barik

Reputation: 57

You can check out this tool for generating pyspark schema from JSON input https://github.com/PreetRanjan/pyspark-schema-generator It helps generating the PySpark schema that you can use in your script and you can add or remove columns as per your requirement. It has few bugs but worked fine for me.

Upvotes: -1

Moritz
Moritz

Reputation: 565

I think I got it. Schemapath contains the already enhanced schema:

schemapath = '/path/spark-schema.json'
with open(schemapath) as f:
   d = json.load(f)
   schemaNew = StructType.fromJson(d)
   jsonDf2 = spark.read.schema(schmaNew).json(filesToLoad)
   jsonDF2.printSchema()

Upvotes: 14

Luiz Viola
Luiz Viola

Reputation: 2416

Why don't you define an empty DF with all columns that the JSON files can have? Then you load the JSONs into it. Here is an idea:

For Spark 3.1.0:

from pyspark.sql.types import *

schema = StructType([
    StructField("fruit",StringType(),True),
    StructField("size",StringType(),True),
    StructField("color",StringType(),True)
])
df = spark.createDataFrame([], schema)

json_file_1 = {"fruit": "Apple","size": "Large"}
json_df_1 = spark.read.json(sc.parallelize([json_file_1]))

df = df.unionByName(json_df_1, allowMissingColumns=True)

json_file_2 = {"fruit": "Banana","size": "Small","color": "Yellow"}

df = df.unionByName(json_file_2, allowMissingColumns=True)

display(df)

Upvotes: 1

Related Questions