任何人都可以看到为什么这不起作用?根据手册的第9.15节,->操作员应该访问JSON数据类型的元素.它在我看来,虽然信息模式说列是类型'json'它仍然是一个标量字符串(注意它显示时的引号.)
postgres=# create table jtest (id serial, data json);
CREATE TABLE
postgres=# select column_name, data_type from information_schema.columns where table_name = 'jtest';
column_name | data_type
-------------+-----------
id | integer
data | json
(2 rows)
postgres=# insert into jtest (data) values (to_json('{"k1": 1, "k2": "two"}'::text));
INSERT 0 1
postgres=# select * from jtest;
id | data
----+--------------------------------
1 | "{\"k1\": 1, \"k2\": \"two\"}"
(1 row)
postgres=# select data->'k1' from jtest;
ERROR: cannot extract element from a scalar
postgres=# select data::json->'k1' from jtest;
ERROR: cannot extract element from a scalar
postgres=# \q
$ pg_ctl --version
pg_ctl (PostgreSQL) 9.3beta2
Run Code Online (Sandbox Code Playgroud)
更新:
我在这里和这里发现了这两个帖子,表明它应该像我一样工作.只是为了确保我试过这个:
postgres=# select * from jtest where data ->> 'k2' = 'two';
ERROR: cannot extract element from a scalar
Run Code Online (Sandbox Code Playgroud)
我需要构建选项或contrib模块来获取JSON功能吗?
我的错误似乎是在插入数据时使用了to_json()函数.这导致了一个包含我的数据的JSON编码字符串.我在postgresql文档中没有找到任何显示如何插入JSON数据的内容,但我最终在这里发现了一个显示示例的帖子.我应该做的:
postgres=# insert into jtest (data) values ('{"k1": 1, "k2": "two"}');
INSERT 0 1
postgres=# select * from jtest;
id | data
----+------------------------
1 | {"k1": 1, "k2": "two"}
(1 row)
Run Code Online (Sandbox Code Playgroud)
(注意数据列中缺少引号.)
它现在有效:
postgres=# select * from jtest where data ->> 'k2' = 'two';
id | data
----+------------------------
1 | {"k1": 1, "k2": "two"}
(1 row)
Run Code Online (Sandbox Code Playgroud)