我认为您的尝试和总体思路是正确的。以下是另外两种基于内置选项的方法,即 get_json_object/from_json 通过数据帧 API 和使用map 转换以及 python 的 json.dumps() 和 json.loads() 通过 RDD API。
选项 1: get_json_object() / from_json()
首先让我们尝试使用不需要架构的get_json_object():
import pyspark.sql.functions as f
df = spark.createDataFrame([
('{"id": 1, "type": "foo", "data": {"key0": "foo", "key2": "meh"}}'),
('{"id": 2, "type": "bar", "data": {"key2": "poo", "key3": "pants"}}'),
('{"id": 3, "type": "baz", "data": {"key3": "moo"}}')
], StringType())
df.select(f.get_json_object("value", "$.id").alias("id"), \
f.get_json_object("value", "$.type").alias("type"), \
f.get_json_object("value", "$.data").alias("data"))
# +---+----+-----------------------------+
# |id |type|data |
# +---+----+-----------------------------+
# |1 |foo |{"key0":"foo","key2":"meh"} |
# |2 |bar |{"key2":"poo","key3":"pants"}|
# |3 |baz |{"key3":"moo"} |
# +---+----+-----------------------------+
相反,from_json() 需要架构定义:
from pyspark.sql.types import StringType, StructType, StructField
import pyspark.sql.functions as f
df = spark.createDataFrame([
('{"id": 1, "type": "foo", "data": {"key0": "foo", "key2": "meh"}}'),
('{"id": 2, "type": "bar", "data": {"key2": "poo", "key3": "pants"}}'),
('{"id": 3, "type": "baz", "data": {"key3": "moo"}}')
], StringType())
schema = StructType([
StructField("id", StringType(), True),
StructField("type", StringType(), True),
StructField("data", StringType(), True)
])
df.select(f.from_json("value", schema).getItem("id").alias("id"), \
f.from_json("value", schema).getItem("type").alias("type"), \
f.from_json("value", schema).getItem("data").alias("data"))
# +---+----+-----------------------------+
# |id |type|data |
# +---+----+-----------------------------+
# |1 |foo |{"key0":"foo","key2":"meh"} |
# |2 |bar |{"key2":"poo","key3":"pants"}|
# |3 |baz |{"key3":"moo"} |
# +---+----+-----------------------------+
选项 2:map/RDD API + json.dumps()
from pyspark.sql.types import StringType, StructType, StructField
import json
df = spark.createDataFrame([
'{"id": 1, "type": "foo", "data": {"key0": "foo", "key2": "meh"}}',
'{"id": 2, "type": "bar", "data": {"key2": "poo", "key3": "pants"}}',
'{"id": 3, "type": "baz", "data": {"key3": "moo"}}'
], StringType())
def from_json(data):
row = json.loads(data[0])
return (row['id'], row['type'], json.dumps(row['data']))
json_rdd = df.rdd.map(from_json)
schema = StructType([
StructField("id", StringType(), True),
StructField("type", StringType(), True),
StructField("data", StringType(), True)
])
spark.createDataFrame(json_rdd, schema).show(10, False)
# +---+----+--------------------------------+
# |id |type|data |
# +---+----+--------------------------------+
# |1 |foo |{"key2": "meh", "key0": "foo"} |
# |2 |bar |{"key2": "poo", "key3": "pants"}|
# |3 |baz |{"key3": "moo"} |
# +---+----+--------------------------------+
函数from_json 会将字符串行转换为(id, type, data) 的元组。 json.loads() 将解析 json 字符串并返回一个字典,我们通过该字典生成并返回最终的元组。