当前位置: 首页 > news >正文

pyspark null类型 在 json.dumps(null) 之后,会变为字符串‘null‘

在将 hive 数仓数据写入 MySQL 时候,有时我们需将数据转为 json 字符串,然后再存入 MySQL。但 hive 数仓中的 null 类型遇到 json 函数之后会变为 ‘null’ 字符串,这时我们只需在使用 json 函数之前对值进行判断即可,当值为 null 时,直接返回 null, 当值非null 时,则使用 json 函数

1 正常情况

在 pyspark 中执行如下代码

history_loc_df = spark.sql("""SELECTuser_id,null as active_points,'20230405'  as ymdFROM tmp.tmp_user"""
export_data_mysql(mysql_result_df)

在这里插入图片描述
将 history_loc_df 数据存入 MySQL,null 数据会为空,如下所示
在这里插入图片描述

2 null 类型变为 ‘null’ 字符串

使用 to_json 函数之后,null 类型会变为 ‘null’ 字符串

def to_json(info):return json.dumps(info)# udf 注册: 转为 json
spark.udf.register("to_json", to_json, StringType())history_loc_df = spark.sql("""SELECTuser_id,to_json(null) as active_points,'20230405'  as ymdFROM tmp.tmp_user"""export_data_mysql(mysql_result_df)

这时将 history_loc_df 数据存入 MySQL,null 数据会变为字符串,如下所示
在这里插入图片描述

3 在 to_json 之前判断是否为空

若想使用 to_json 函数,当遇到 null 值,返回 null 类型,遇到其它值则转为 json 字符串

只需要在转为 json 字符串之前对值进行判断即可

def to_json(info):return json.dumps(info)# udf 注册: 转为 json
spark.udf.register("to_json", to_json, StringType())history_loc_df = spark.sql("""SELECTuser_id,if(active_points is null, null, to_json(null)) as active_points,'20230405'  as ymdFROM tmp.tmp_user"""
export_data_mysql(mysql_result_df)
http://www.lryc.cn/news/58000.html

相关文章:

  • LeetCode - 两数相加
  • Office 2021专业版安装包及激活教程
  • git版本规范-前端
  • UEFI Device Path (1): 重新认识Device Path
  • 合成孔径成像的应用及发展
  • MyBatis-Plus的基本操作
  • HTTPAPI使用
  • Windos下设置java项目开机自启动
  • (链表)移除链表元素(双指针法)
  • Raft协议
  • 动态规划概述
  • CPU缓存架构+Disruptor内存队列
  • Spark SQL join操作详解
  • 设计模式-day04
  • 线段树的学习(2023.4.5)
  • Java 实现excel、word、txt、ppt等办公文件在线预览功能
  • 《Vue3实战》 第九章 路由
  • ToBeWritten之物联网Zigbee协议
  • 【万象奥科】RZ/G2UL网关内存压力测试
  • C++中的继承
  • SpringRetry接口异常优雅重试机制
  • 2023年全国最新高校辅导员精选真题及答案46
  • 程序员为了女朋you进了华为,同学去了阿里,2年后对比收入懵了
  • Linux中的算法分离手段
  • 机器学习实战:Python基于Logistic逻辑回归进行分类预测
  • Leetcode.404 左叶子之和
  • Android 11.0 原生SystemUI下拉通知栏UI背景设置为圆角背景的定制(二)
  • C语言CRC-16 IBM格式校验函数
  • Maven高级-聚合和继承
  • 如何写出10万+ Facebook 贴文?