尝试将多个 json 文件读入数据帧,两个文件都有一个“Value”节点,但该节点的类型在整数和结构之间交替:
File 1:
{
"Value": 123
}
File 2:
{
"Value": {
"Value": "On",
"ValueType": "State",
"IsSystemValue": true
}
}
我的目标是将文件读入数据帧,如下所示:
|---------------------|------------------|---------------------|------------------|
| File | Value | ValueType | IsSystemValue |
|---------------------|------------------|---------------------|------------------|
| File1.json | 123 | null | null |
|---------------------|------------------|---------------------|------------------|
| File2.json | On | State | true |
|---------------------|------------------|---------------------|------------------|
有可能所有读取的文件都像 FileA 而没有像 FileB,反之亦然,或者两者的组合。提前不知道。有任何想法吗??
试试这是否有帮助 -
加载测试数据
/**
* test/File1.json
* -----
* {
* "Value": 123
* }
*/
/**
* test/File2.json
* ---------
* {
* "Value": {
* "Value": "On",
* "ValueType": "State",
* "IsSystemValue": true
* }
* }
*/
val path = getClass.getResource("/test" ).getPath
val df = spark.read
.option("multiLine", true)
.json(path)
df.show(false)
df.printSchema()
/**
* +-------------------------------------------------------+
* |Value |
* +-------------------------------------------------------+
* |{"Value":"On","ValueType":"State","IsSystemValue":true}|
* |123 |
* +-------------------------------------------------------+
*
* root
* |-- Value: string (nullable = true)
*/
转换字符串 json
df.withColumn("File", substring_index(input_file_name(),"/", -1))
.withColumn("ValueType", get_json_object(col("Value"), "$.ValueType"))
.withColumn("IsSystemValue", get_json_object(col("Value"), "$.IsSystemValue"))
.withColumn("Value", coalesce(get_json_object(col("Value"), "$.Value"), col("Value")))
.show(false)
/**
* +-----+----------+---------+-------------+
* |Value|File |ValueType|IsSystemValue|
* +-----+----------+---------+-------------+
* |On |File2.json|State |true |
* |123 |File1.json|null |null |
* +-----+----------+---------+-------------+
*/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)