如何在PostgreSQL中根据Key从JSON字符串获取对应Value
问题描述
数据库表t1的data列存储着格式为[{"K":"V"}]的JSON字符串,尝试使用以下SQL语句根据Key获取对应Value时,出现语法错误:
select Value ->> 'Value' from json_array_elements(select data from t1) Key where Key->>'Key'='K';
可行解决方案
- 创建表:
CREATE TABLE t1 ( id int, data json );
- 向
t1表插入测试数据:
insert into t1 values (1,'[{"K":"V"}]'), (2,'[{"loadShortCut_AutoText":"both"}]'), (3,'[{"P":"R"}]');
- 使用以下查询语句获取目标结果:
select row, row->>'loadShortCut_AutoText' as value from t1, json_array_elements (t1.data) as row WHERE t1.id=2;
- 查询结果:
{"loadShortCut_AutoText":"both"} both
内容的提问来源于stack exchange,提问作者Shantilal Suthar
相关产品推荐
相关产品推荐

