无法解析Service-Now JSON数据 用Python/Scala读取数湖JSON失败求助
问题根因
解析后出现空值的核心原因有两点:
- JSON文件中存在大量非法格式的字段值,比如
sys_updated_on的207-07-0 02:3:3、sys_created_on的203-2-04 2:34:08均不符合标准日期格式,Spark默认的类型推断机制无法解析这类值,会将对应字段赋值为null scaled_value、weighted_value、normalized_value等数值类字段以字符串格式存储,类型推断过程中也容易出现匹配异常
解决方案
按照以下步骤修改读取代码即可正常解析内容:
- 指定自定义schema读取,跳过自动类型推断步骤,避免类型匹配错误,Scala示例代码如下:
import org.apache.spark.sql.types._ // 定义和JSON结构完全匹配的自定义Schema val customSchema = StructType(Seq( StructField("result", ArrayType(StructType(Seq( StructField("instance", StructType(Seq( StructField("link", StringType), StructField("value", StringType) ))), StructField("string_value", StringType), StructField("assign_to_order", StringType), StructField("instance_question", StructType(Seq( StructField("link", StringType), StructField("value", StringType) ))), StructField("template_definition", StringType), StructField("metric_definition", StructType(Seq( StructField("link", StringType), StructField("value", StringType) ))), StructField("sys_updated_on", StringType), StructField("scaled_value", StringType), StructField("metric", StructType(Seq( StructField("link", StringType), StructField("value", StringType) ))), StructField("sys_created_on", StringType), StructField("sys_domain", StructType(Seq( StructField("link", StringType), StructField("value", StringType) ))), StructField("weighted_value", StringType), StructField("source_id", StructType(Seq( StructField("link", StringType), StructField("value", StringType) ))), StructField("normalized_value", StringType), StructField("source_table", StringType), StructField("user", StringType), StructField("sys_created_by", StringType) )))) )) val asmt_metric_result = spark.read .option("multiline", "true") .option("mode", "PERMISSIVE") .schema(customSchema) .json("c:/servicenow/asmt_metric_result/2021/09/28/08/32/asmt_metric_result_000000.json") asmt_metric_result.show(false)
- 读取完成后,可单独对日期类字段做格式清洗,对数值类字段做类型转换即可正常使用数据。
参考附件




内容的提问来源于stack exchange,提问作者user3482527
相关产品推荐
相关产品推荐

