Я пытаюсь получить схему Pyspark
из файла JSON, но когда я создаю схему с использованием переменной в коде Python, я могу видеть тип переменной <class 'pyspark.sql.types.StructType'>
но когда я Я пытаюсь получить через JSON файл, показывающий тип unicode
.
Есть ли способ получить схему pyspark
через JSON файл?
Содержимое файла JSON:
{
"tediasessionclose_schema" : "StructType([ StructField('@timestamp', StringType()), StructField('message' , StructType([ StructField('componentAddress', StringType()), StructField('values', StructType([ StructField('confNum', StringType()), StructField('day', IntegerType())])"
}
Код Pyspark:
df = sc.read.json(hdfs_path, schema = jsonfile['tediasessionclose_schema'])
файл config_json:
{"json_data_schema": ["contactId", "firstName", "lastName"]}
Приложение PySpark:
schema = StructType().add("contactId", StringType()).add("firstName", StringType()).add("lastName", StringType())
Ссылка: https://www.python-course.eu/lambda.php
schema = StructType()
schema = map(lambda x: schema.add(x, StringType(), True), (data["json_data_schema"]))[0][0:]
Надеюсь, что это решение работает для вас!
Вы можете получить схему, оценив строку, которую вы получаете от чтения json:
import json
from pyspark.sql.types import StructField, StringType, IntegerType, StructType
with open('test.json') as f:
data = json.load(f)
df = sqlContext.createDataFrame([], schema = eval(data['tediasessionclose_schema']))
print(df.schema)
выходы:
StructType(List(StructField(@timestamp,StringType,true),StructField(message,StructType(List(StructField(componentAddress,StringType,true),StructField(values,StructType(List(StructField(confNum,StringType,true),StructField(day,IntegerType,true))),true))),true)))
где test.json
:
{"tediasessionclose_schema" : "StructType([ StructField('@timestamp', StringType()), StructField('message' , StructType([ StructField('componentAddress', StringType()), StructField('values', StructType([ StructField('confNum', StringType()), StructField('day', IntegerType())]))]))])"}
Надеюсь это поможет!