繁体   English   中英

Pyspark从JSON文件获取架构

[英]Pyspark get Schema from JSON file

我试图从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'])

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

希望这可以帮助!

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

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM