可以使用DataFrame的read功能将JSON文件加载到
Spark
数据框中,并使用“ StructType”和“ StructField”从嵌套中定义JSON模式。然后可以使用“ get_json_object”和“ from_json”
函数
来
解析
嵌套的JSON数据。
示例代码:
from py
spark
.sql.functions import *
from py
spark
.sql.types import *
定义JSON模式
jsonSchema = StructType([
StructField('name', StringType(), True),
StructField('age', IntegerType(), True),
StructField('address', StructType([
StructField('street', StringType(), True),
StructField('
ci
ty', StringType(), True),
StructField('state', StringType(), True)
从JSON文件中读取数据
df =
spark
.read
.option("multiline", "true")
.option("inferSchema", "false")
.schema(jsonSchema)
.json("/path/to/nested.json")
解析
嵌套的JSON数据
df = df.select("name", "age",
col("address.street").ali
as
("street"),
col("address.
ci
ty").alias("
ci
ty"),
col("address.state").ali
as
("state"))
显示
解析
后的数据
df.show()