PostgreSQL中的json解析

  • 1、PostgreSQL json 数组解析
-- INSERT INTO "dwd"."dwd_test"(id, cname, is_deleted)
-- 数据格式为:[{}, {}, ...]
-- 字典的 key='value'
-- cnames 为需要解析的字段
SELECT 
	id,
	(CASE 
		WHEN cnames LIKE '%}]' 
		THEN json_array_elements(REPLACE(cnames, '\u0000', '')::json)->>'value' 
	END) AS cname,
	is_deleted
from 
	"ods"."ods_test"
WHERE
	is_deleted='f'
  	AND cnames LIKE '%}]'

注意:::json也可以用json(xxx)代替

  • 2、MySQL json 数组解析
-- [{}, {}, ...]
-- 用json_unquote函数去掉双引号,而不是replace,哪种更优雅一目了然。但是我认为 ->> 最优雅。
SELECT json_unquote(json_extract( a, '$[0]."text"' ))  AS b FROM `table_name` WHERE id=424;
SELECT json_unquote(json_extract( a, '$[*]."text"' ))  AS b FROM `table_name` WHERE id=424;
SELECT a ->> '$[0].text' AS b FROM `table_name` WHERE id=424;
SELECT a ->> '$[*].text' AS b FROM `table_name` WHERE id=424;
SELECT REPLACE(a ->> '$[*].text','\",\",','')  AS b FROM `table_name` WHERE id=424;
  • PostgreSQL 取json的第一个元素
假设要解析的json字段名为json_field
若json_field格式为:[[10], [20, 30]]
SELECT json_field -> 0;

若json_field格式为:[{'key': value}]
SELECT json_field -> 0 ->>'key' FROM table_name;

PostgreSQL JSON字段的 ->> #>> 取值操作

SELECT
data#>>‘{_id, $oid}’ as trace_id,
cast(data#>>‘{cid, $numberLong}’ as int8) as cid,
cast(data#>>‘{sid, $numberLong}’ as int8) as sid,
cast(data#>>‘{percent, $numberDecimal}’ as numeric(40, 10)) as percent,
cast(data->>‘is_deleted’ as bool) as is_deleted
FROM “ods”.“ext_ods_mongo_t_xxxt”;

– 测试发现第一层是json,第二层是text。
select data, pg_typeof(data) FROM “ods”.“ext_ods_mongo_t_xxx” limit 1;
select data, pg_typeof(data->>‘_id’) as _id FROM “ods”.“ext_ods_mongo_t_xxx” limit 1;
#>>表示获取指定路径的一个JSON对象的字符串
SELECT data#>>‘{_id, $oid}’ as trace_id

https://blog.csdn.net/wangzhi291/article/details/102485976

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值