[英]Postgres | V9.4 | Extract value from json
I have a table that one of the columns is in type TEXT and holds a json object inside.我有一个表,其中一列的类型为 TEXT 并在其中包含一个 json 对象。 I what to reach a key inside that json and ask about it's value.我如何到达该 json 中的一个键并询问它的价值。 The column name is json_representation and the json looks like that:列名是 json_representation 并且 json 看起来像这样:
{
"additionalInfo": {
"dbSources": [{
"user": "Mike"
}]
}
}
I want to get the value of the "user" and ask if it is equal to "Mike".我想获取“用户”的值并询问它是否等于“迈克”。 I tried the following:我尝试了以下方法:
select
json_representation->'additionalInfo'->'dbSources'->>'user' as singleUser
from users
where singleUser = 'Mike';
I keep getting an error: Query execution failed我不断收到错误消息:查询执行失败
Reason: SQL Error [42883]: ERROR: operator does not exist: text -> unknown Hint: No operator matches the given name and argument type(s).原因:SQL 错误 [42883]:错误:运算符不存在:文本 -> 未知 提示:没有运算符匹配给定的名称和参数类型。 You might need to add explicit type casts.您可能需要添加显式类型转换。 Position: 31职位:31
please advice Thanks请指教谢谢
The error message tells you what to do: you might need to add an explicit type cast :错误消息告诉您该怎么做:您可能需要添加显式类型转换:
And as you can not reference a column alias in the WHERE clause, you need to wrap it into a derived table:由于您不能在 WHERE 子句中引用列别名,您需要将其包装到派生表中:
select *
from (
select json_representation::json ->'additionalInfo'->'dbSources' -> 0 ->>'user' as single_user
from users
) as t
where t.single_user = 'Mike';
::
is Postgres' cast operator ::
是 Postgres 的转换运算符
But the better solution would be to change the column's data type to json
permanently.但更好的解决方案是将列的数据类型永久更改为json
。 And once you upgrade to a supported version of Postgres, you should use jsonb
.一旦升级到受支持的 Postgres 版本,就应该使用jsonb
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.