【问题标题】:reading JSON with custom schema - pyspark使用自定义模式读取 JSON - pyspark
【发布时间】:2023-01-20 04:45:11
【问题描述】:

使用自定义模式读取 JSON 时,它会为我提供所有 NULL 值。我知道原因(因为实际数据类型与自定义模式类型不匹配)但我不知道如何修复它(除了读取它 with open 方法)。我想让你阅读 JSON 模块。

spark = SparkSession \
        .builder \
        .appName("JSON test") \
        .getOrCreate()
    
schema = StructType([StructField("_links", MapType(StringType(), MapType(StringType(), StringType()))),
                         StructField("identifier", StringType()),
                         StructField("enabled", BooleanType()),
                         StructField("family", StringType()),
                         StructField("categories", ArrayType(StringType())),
                         StructField("groups", ArrayType(StringType())),
                         StructField("parent", StringType()),
                         StructField("values", MapType(StringType(), ArrayType(MapType(StringType(), StringType())))),
                         StructField("created", StringType()),
                         StructField("updated", StringType()),
                         StructField("associations", MapType(StringType(), MapType(StringType(), ArrayType(StringType())))),
                         StructField("quantified_associations", MapType(StringType(), IntegerType())),
                         StructField("metadata", MapType(StringType(), StringType()))])
    
df = spark.read.format("json") \
            .schema(schema) \
            .load(f'/mnt/bronze/products/**/*.json')
df.display()

【问题讨论】:

    标签: json apache-spark pyspark


    【解决方案1】:

    在您的第一遍数据中,我建议以原始格式读取数据,例如,如果布尔值在 json 中,如 {"enabled" : "true"},我会将伪布尔值读取为字符串(因此将您的 BooleanType() 更改为 @987654323 @) 然后在成功读入后在后续步骤中将其转换为布尔值。

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 2021-06-19
      • 1970-01-01
      • 2021-02-20
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2021-03-30
      相关资源
      最近更新 更多