0

我面临一个奇怪的问题,我正在尝试显示我的 JSON 对象的值,它可以正常工作,select()但不能正常工作selectExp(),我收到一个奇怪的错误,在我的实现中,

from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.functions import col

spark = SparkSession.builder.appName("JsonPractice").getOrCreate()
my_json_df = spark.range(1).selectExpr(
    """'{"sample_json":{"sample_json1":["1st_vale","2nd_val"]}}' as my_json_column""")
my_json_df.selectExpr(get_json_object(col("my_json_column"), "$.sample_json.sample_json1[1]")).show(2)
my_select_expr = get_json_object(col('my_json_column'), '$.sample_json.sample_json1')
my_json_df.selectExpr(my_select_expr).show()

我收到以下错误

raise TypeError("Column is not iterable")
TypeError: Column is not iterable

4

1 回答 1

0

col我们在使用时不需要指定selectExpr

my_select_expr = "get_json_object(my_json_column, '$.sample_json.sample_json1')"
my_json_df.selectExpr(my_select_expr).show(10,False)

#or    
my_json_df.selectExpr("get_json_object(my_json_column,'$.sample_json.sample_json1')").show(10,False)
#+-----------------------------------------------------------+
#|get_json_object(my_json_column, $.sample_json.sample_json1)|
#+-----------------------------------------------------------+
#|["1st_vale","2nd_val"]                                     |
#+-----------------------------------------------------------+

UPDATE:

from pyspark.sql.functions import *
my_select_expr=get_json_object(col('my_json_column'),'$.sample_json.sample_json1')
my_json_df.select(my_select_expr).show(10,False)
#+-----------------------------------------------------------+
#|get_json_object(my_json_column, $.sample_json.sample_json1)|
#+-----------------------------------------------------------+
#|["1st_vale","2nd_val"]                                     |
#+-----------------------------------------------------------+
于 2020-07-09T14:20:43.280 回答