gpt4 book ai didi

python - Pyspark 从 JSON 文件获取架构

转载 作者:行者123 更新时间:2023-12-01 01:47:09 25 4
gpt4 key购买 nike

我正在尝试获取 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'])

最佳答案

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

希望这有帮助!

关于python - Pyspark 从 JSON 文件获取架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51185303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com