pgsql实现json格式转换

1.需要转换的json数据,json对象嵌套json数组

{
        "recordMethod1": {
                "method": "1",
                "methodDisplay": "1",
                "convertFormula": "",
                "valueTitle": "",
                "points": [{
                        "minValue": "12",
                        "maxValue": "23"
                }, {
                        "minValue": "22",
                        "maxValue": "24"
                }]
        },
        "recordMethod2": {
                "method": "2",
                "methodDisplay": "2",
                "convertFormula": "3",
                "valueTitle": "",
                "points": [{
                        "minValue": "12",
                        "maxValue": "23"
                }, {
                        "minValue": "22",
                        "maxValue": "24"
                }]
        }
}

        这是我进行操作的表结构如下:

表名:record_speed
record_method_detailtext集合列表
record_idvarchar唯一标识

2.首先对json对象进行解析转换

(对json对象进行查询)对recordMethod1和recordMethod2使用别名来查询显示

select 
record_method_detail::json -> 'recordMethod1' as method1,
record_method_detail::json -> 'recordMethod2' as method2,
from record_speed
where record_id='01' and record_method_detail <> ''

查询结果如下:查询出来的是对象形式

(查询json对象对应的属性转换)对某个对象的属性进行分属性查询数据

select 
record_method_detail::json -> 'recordMethod1'->> 'method' as method,
record_method_detail::json -> 'recordMethod1'->> 'methodDisplay'as methodDisplay,
record_method_detail::json -> 'recordMethod1'->> 'convertFormula' as convertFormula,
record_method_detail::json -> 'recordMethod1'->> 'valueTitle'as valueTitle
from record_speed
where record_id='01' and record_method_detail <> ''

 查询结果:recordMethod1的json对象属性

(查询recordMethod1json对象的points的json数组)把recordMethod1对象里面的“points”数组对象使用jsonb_array_elements解析成数组来查询

select 
two->> 'minValue' as minValue,
two->> 'maxValue' as maxValue
from record_speed,jsonb_array_elements(
(select 
(record_method_detail::json->'recordMethod1')->>'points' as method1 
from record_speed where record_id='12')::jsonb) two
where record_id='12' and record_method_detail <> ''

-- 要校验该属性字段是否非空,如果为空进行转换会报空指针错误
--jsonb_array_elements 解析json数组转成多行

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值