如何获取PostgreSQL数据库中的JSON值
在PostgreSQL数据库中有一列为JSON,要获取JSON中得数据可以用下面sql:
selectordernoasOrderNo ,amountasAmount ,ordertimeasOrderTime ,recordtypeasRecordType fromjsonb_to_recordset((--特定方法 selectarray_to_json(array_agg(data))--转换成一个数组 fromwallet_details whereid=@id )::jsonb)asx(ordernotext,amountnumeric(16,6),ordertimetext,recordtypevarchar(32));
如果你获取得数据是当前行,但是JSON中也要取出来几个值可以用下面的方式获取:
selectpay_params::json->>'Key'asMd5Key, pay_params::json->>'AppId'asAppid, pay_params::json->>'MchId'asMchid, pay_params::json->>'SubMchId'asSubmchid, tenant_idasTenant_Id fromspm_wallet_settingswhereid='12'
补充:PostgreSql数据库sql语句取Json值
1:json字段实例:
{
“boxNum”:0,
“orderNum”:0,
“commentNum”:0
}
A.取boxNum的值
1.1)select字段名->‘boxNum'from表名;
1.2)selectjsonb_extract_path_text字段名,‘boxNum')from表名;
2:json字段实例:
{
“boxNum”:“0”,
“orderNum”:“0”,
“commentNum”:“0”
}
A.取boxNum的值,不带双引号。
2.1)select字段名->>‘boxNum'from表名;
2.2)selectjsonb_extract_path_text字段名,‘boxNum')from表名;
3:json字段实例:
{
“unitPrices”:[{
“price”:10.0,
“unitId”:“8”,
“unitName”:“500克”,
“unitAmount”:“0”,
“isPMDefault”:true,
“isHomeDefault”:true,
“originalPrice”:10.0
}],
“productName”:“远洋加拿大螯龙虾野生捕捞”,
“productType”:1,
“skuPortRate”:{
“id”:“a6b83048-3878-4698-88c2-2a9de288ac56”,
“cityId”:“2bf8c60c-789d-433a-91ae-8e4ae3e587a4”,
“dynamicProperties”:[{
“name”:“死亡率”,
“propertiesId”:“f05bda8c-f27c-4cc6-b97e-d4bd07272c81”,
“propertieValue”:{
“value”:“2.0”
}
},{
“name”:“失水率”,
“propertiesId”:“ee9d95d7-7e28-4d54-b572-48ae64146c46”,
“propertieValue”:{
“value”:“3.0”
}
}]
},
“quotePriceAttribute”:{
“currencyName”:“人民币”
}
}
A.取quotePriceAttribute中的currencyName币制名称
select(字段名>>‘quotePriceAttribute')::json->>‘currencyName'from表名;
B.取unitPrices中的price单价
selectjsonb_array_elements((字段名->>‘unitPrices')::jsonb)->>‘price'from表名;
C.取skuPortRate中的dynamicProperties的name为死亡率的propertieValue里面的value;
selectbb->‘propertieValue'->>‘value'asvaluefrom(
selectjsonb_array_elements(((字段名->>‘skuPortRate')::json->>‘dynamicProperties')::jsonb)asbbfrom表名)asddwheredd.bb@>‘{“name”:“死亡率”}';
4.json字段实例:
[{“name”:“捕捞方式”,“showType”:4,“propertiesId”:“9a14e435-9688-4e9b-b254-0e8e7cee5a65”,
“propertieValue”:{“value”:“野生捕捞”,“enValue”:“Wild”}},
{“name”:“加工方式”,“showType”:4,“propertiesId”:“7dc101df-d262-4a75-bdca-9ef3155b7507”,
“propertieValue”:{“value”:“单冻”,“enValue”:“IndividualQuickFreezing”}},
{“name”:“原产地”,“showType”:4,“propertiesId”:“dc2b506e-6620-4e83-8ca1-a49fa5c5077a”,
“propertieValue”:{“value”:“爱尔兰”,“remark”:“”,“enValue”:“Ireland”}}]
–获取原产地
select
(SELECTss->‘propertieValue'asmmFROM
(SELECTjsonb_array_elements(dynamic_properties)ASssFROMproduct
whereid=a.id)asddwheredd.ss@>‘{“name”:“原产地”}')->>‘value'ascuntry,
a.*
fromproductasawherea.id=‘633dd80f-7250-465f-8982-7a7f01aaeeec';
5:json例子:huren:[“aaa”,“bbb”,“ccc”…]
需求:取值aaa去““双引号”
selectreplace(cast(jsonb_array_elements(huren)astext),‘"','')fromXXXlimit1
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。