PostgreSQL 9.3+的JSON,它是如此丑陋?

时间:2015-11-29 19:23:25

标签: json postgresql

text s和整数作为int s获取字符串有一种“不太难看”的选项?

JSON树的所有叶子都有众所周知的数据类型,那么,如何对PostgreSQL说看数据类型呢?

问题和UGLY解决方案的例子......解决方案不那么难看?

SELECT version(); -- PostgreSQL 9.3

CREATE TABLE example (
  id serial PRIMARY KEY,
  info JSON 
);
INSERT INTO example (info) VALUES
  ('{"aa":10,"bb":"nonono nononon"}'),
  ('{"aa":10,"x":"etc"}'),  
  ('{"aa":9,"x":"etc etc"}');

-- SIX ERROS... But human-readable syntax
SELECT DISTINCT info->'aa' FROM example;    -- ex.1
SELECT * FROM example ORDER BY info->'aa';  -- ex.2
SELECT info->'x' FROM example WHERE info->'x' IS NOT NULL; -- ex.3
SELECT * FROM example WHERE info->'x'='etc';  -- ex.4
SELECT * FROM example WHERE (info->'x')::text='etc';  -- ex.5
SELECT * FROM example WHERE info->'aa'=10;  -- ex.6

-- UGLY (!!) six workarounds
SELECT DISTINCT (info->'aa')::text FROM example;        -- ex.1
SELECT * FROM example ORDER BY (info->'aa')::text::int; -- ex.2
SELECT info->'x' FROM example WHERE (info->'x')::text IS NOT NULL; -- ex.3
SELECT * FROM example WHERE trim((info->'x')::text,'"')='etc';  -- exs. 4 and 5
SELECT * FROM example WHERE (info->'aa')::text::int=10;  -- ex.6

1 个答案:

答案 0 :(得分:3)

使用->> json operator,它将JSON对象字段或JSON数组作为text返回。

SELECT DISTINCT info->>'aa' FROM example;
SELECT * FROM example ORDER BY info->>'aa';
SELECT info->>'x' FROM example WHERE (info->>'x') IS NOT NULL;
SELECT * FROM example WHERE info->>'x'='etc';
SELECT * FROM example WHERE (info->>'aa')::int=10;  -- still needs a cast to int