Pyspark从JSON文件获取架构

时间:2018-07-05 07:12:28

标签: python json apache-spark pyspark

我正在尝试从JSON文件中获取Pyspark模式,但是当我使用Python代码中的变量创建模式时,我可以看到<class 'pyspark.sql.types.StructType'>的变量类型,但是当我我试图通过JSON文件来显示unicode的类型。

是否可以通过JSON文件获取pyspark模式?

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'])

2 个答案:

答案 0 :(得分:1)

您可以通过评估读取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())]))]))])"}

希望这会有所帮助!

答案 1 :(得分:1)

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:]

希望此解决方案对您有用!