【问题标题】:Aggregate columns and change to a ArrayType schema in pyspark在 pyspark 中聚合列并更改为 ArrayType 模式
【发布时间】:2021-06-10 21:15:30
【问题描述】:

我想聚合一些列并以特定的模式格式对其进行修改

id name_en name_sp name_fr
1 hello hello_spanish hello_french

我想要结构格式的名称,这样当我调用 json.dumps 或 to_json 时,它会被转换为适当的 json 对象。

我正在使用这个 ArrayType

schema = ArrayType(StructType([StructField("locale", StringType(), True),StructField("value", StringType(), True)]))

最好我想将其转换为结构数组,以便当我在整个表上调用 json.dumps 时,它会将其转换为以下 Json 对象

{
 "id" : 1,
  "names" : [{"locale" : "en", "value" : "hello"}, {"locale" : "sp", "value" : "hello_spanish"}, {"locale" : "fr", "value" : "hello_french"}]
} 

它不会变成带有字符串和转义字符的jsonObject。

{
 "id" : 1,
  "names" : "[{\\"locale\\" : \\"en\\", \\"value\\" : \\"hello\\"}, {\\"locale\\" : \\"sp\\", \\"value\\" : \\"hello_spanish\\"}, {\\"locale\\" : \\"fr\\", \\"value\\" : \\"hello_french\\"}]"
}

【问题讨论】:

    标签: python json apache-spark pyspark apache-spark-sql


    【解决方案1】:

    您可以将结构数组构造为:

    df2 = df.selectExpr(
        'id', 
        """
        array(
            struct('en' as locale, name_en as value),
            struct('sp' as locale, name_sp as value),
            struct('fr' as locale, name_fr as value)
        ) as names
        """
    )
    
    df2.show(truncate=False)
    +---+------------------------------------------------------+
    |id |names                                                 |
    +---+------------------------------------------------------+
    |1  |[[en, hello], [sp, hello_spanish], [fr, hello_french]]|
    +---+------------------------------------------------------+
    

    要获取为 JSON,您可以尝试:

    df2.toJSON().collect()
    
    # this gives:
    # ['{"id":1,"names":[{"locale":"en","value":"hello"},
    #   {"locale":"sp","value":"hello_spanish"},
    #   {"locale":"fr","value":"hello_french"}]}']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多