嵌套Json提取中间未知键的值

Posted

技术标签:

【中文标题】嵌套Json提取中间未知键的值【英文标题】:Nested Json extract the value with unknown key in the middle 【发布时间】:2021-08-26 21:58:28 【问题描述】:

我在这样的数据框中有一个 Json 列(colJson)


    "a": "value1",
    "b": "value1",
    "c": true,
    "details": 
        "qgiejfkfk123":  //unknown value
            "model1": 
                "score": 0.531,
                "version": "v1"
            ,
            "model2": 
                "score": 0.840,
                "version": "v2"
            ,
            "other_details": 
                "decision": false,
                "version": "v1"

            
        
    

这里的 'qgiejfkfk123' 是动态值,并且随每一行而变化。但是我需要提取 model1.score 和 model2.score。

我试过了

sourceDf.withColumn("model1_score",get_json_object(col("colJson"), "$.details.*.model1.score").cast(DoubleType))
.withColumn("model2_score",get_json_object(col("colJson"), "$.details.*.model2.score").cast(DoubleType))

但没用。

【问题讨论】:

不确定我是否做错了什么。但对我不起作用。试过了。 sourceDf.withColumn("model1_score",get_json_object(col("colJson"), "$.details..model1.score").cast(DoubleType)) .withColumn("model2_score",get_json_object(col("colJson"), "$.details..model2.score").cast(DoubleType)) 嗯,jsonpath 通配符返回列表。我没有意识到的是 Spark 的 jsonPath 实现不支持按索引引用列表元素,例如$.details..model1[0].score。不知道可以在这里做什么,对不起,但好问题! 【参考方案1】:

我设法通过使用from_json 获得您的解决方案,将动态值解析为 Map 并从中分解值:

val schema = "STRUCT<`details`: MAP<STRING, STRUCT<`model1`: STRUCT<`score`: DOUBLE, `version`: STRING>, `model2`: STRUCT<`score`: DOUBLE, `version`: STRING>, `other_details`: STRUCT<`decision`: BOOLEAN, `version`: STRING>>>>"

val fromJsonDf = sourceDf.withColumn("colJson", from_json(col("colJson"), lit(schema)))
val explodeDf = fromJsonDf.select($"*", explode(col("colJson.details")))
// +----------------------------------------------------------+------------+--------------------------------------+
// |colJson                                                   |key         |value                                 |
// +----------------------------------------------------------+------------+--------------------------------------+
// |qgiejfkfk123 -> 0.531, v1, 0.84, v2, false, v1|qgiejfkfk123|0.531, v1, 0.84, v2, false, v1|
// +----------------------------------------------------------+------------+--------------------------------------+

val finalDf = explodeDf.select(col("value.model1.score").as("model1_score"), col("value.model2.score").as("model2_score"))
// +------------+------------+
// |model1_score|model2_score|
// +------------+------------+
// |       0.531|        0.84|
// +------------+------------+

【讨论】:

以上是关于嵌套Json提取中间未知键的值的主要内容,如果未能解决你的问题,请参考以下文章

在python的嵌套json字典中查找一个值

PHP:嵌套 json 和值提取

Oracle 使用带有 oracle regexp_substr 的正则表达式提取 json 字段

Bigquery:是不是有一种 json 路径方法可以仅从具有动态键的 json 数组中提取值?

从熊猫数据框中提取嵌套字典

从 Google Ads BigQuery 数据传输中提取/取消嵌套数组