解析Python Sp中表列中存储的JSON

2024-09-28 03:18:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析JSON并使用Python Spark向数据帧添加列:

tableDF = spark.sql("select  * from transaction")

stats_df = parseJSONCols(tableDF)

def parseJSONCols(df):
    res = df
    cols = ['State']

    for i in cols:
        schema = spark.read
            .json(res.rdd.map(lambda x: x[i]))
            .schema
        res = res.withColumn("selectedState", lit(filterSelectedState(col(i))))

    return res

其中State是具有以下结构的JSON字符串:

[
    {
        isSelected: true,
        name: 'x'
    },
    {
        isSelected: false,
        name: 'y'
    }
]

我想提取isSelected字段的值,并将其添加到tableDFselected列中。你知道吗

有人能帮我做到这一点吗?你知道吗


Tags: 数据namejsondfsqlschemaresselect
1条回答
网友
1楼 · 发布于 2024-09-28 03:18:51

你可能想要这样的东西:

df = df.withColumn('isSelected', f.col('State').getItem('isSelected'))

但是,查看saystats_df.take(2)的输出会很有用,这样我们就可以看到您正在处理的DF的确切结构。你知道吗

相关问题 更多 >

    热门问题