Postgres | V9.4 |从json中提取值

问题描述 投票:0回答:1

我有一个表,其中的列之一为TEXT类型,并且其中包含一个json对象。我怎样才能到达json中的键并询问其值。列名是json_representation,而json看起来像这样:

{
    "additionalInfo": {
        "dbSources": [{
            "user": "Mike"
        }]
    }
}

我想获取“用户”的值,并询问它是否等于“迈克”。我尝试了以下方法:

select
json_representation->'additionalInfo'->'dbSources'->>'user' as singleUser 
from users 
where singleUser = 'Mike';

我不断收到错误消息:查询执行失败

原因:SQL错误[42883]:错误:运算符不存在:文本->未知提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。位置:31

请咨询谢谢

sql json postgresql postgresql-9.4
1个回答
1
投票

错误消息告诉您该怎么做:您可能需要添加显式类型转换

并且由于无法在WHERE子句中引用列别名,因此需要将其包装到派生表中:

select *
from (
   select json_representation::json ->'additionalInfo'->'dbSources' -> 0  ->>'user' as single_user 
   from users 
) as t
where t.single_user = 'Mike';

[::是Postgres的cast operator

但是更好的解决方案是将列的数据类型永久更改为json。而且,一旦升级到Postgres的受支持版本,就应该使用jsonb

© www.soinside.com 2019 - 2024. All rights reserved.