查询保存在Postgres中的Json数据

时间:2017-01-13 20:48:21

标签: json postgresql

我试图查询保存在postgres中的JSON数据。 这是表的创建方式

CREATE TABLE ALARMDATA2(ALARM        CHAR(1300))

这是JSON对象:

{"delay_max": 0.0, "ts_errors": [{"count": 0, "state": 0, "is_priority1": true, "name": "SYNC", "is_priority2": false}, {"count": 0, "state": 0, "is_priority1": true, "name": "BYTE", "is_priority2": false}, {"count": 0, "state": 0, "is_priority1": true, "name": "PAT", "is_priority2": false}, {"count": 0, "state": 0, "is_priority1": true, "name": "CC", "is_priority2": false}, {"count": 0, "state": 0, "is_priority1": true, "name": "PMT", "is_priority2": false}, {"count": 0, "state": 0, "is_priority1": true, "name": "PID", "is_priority2": false}, {"count": 0, "state": 0, "is_priority1": false, "name": "TS", "is_priority2": true}, {"count": 0, "state": 0, "is_priority1": false, "name": "CRC", "is_priority2": true}, {"count": 0, "state": 0, "is_priority1": false, "name": "PCR", "is_priority2": true}, {"count": 0, "state": 0, "is_priority1": false, "name": "ACC", "is_priority2": true}, {"count": 0, "state": 0, "is_priority1": false, "name": "PTS", "is_priority2": true}, {"count": 0, "state": 0, "is_priority1": false, "name": "CAT", "is_priority2": true}], "is_stream_paused": false, "delay_min": 0.0, "ac_err": 0.0, "oj_err": 0.0}

我想根据" delay_max"进行查询(JSON中的第一个条目)。我正在使用此查询

SELECT ALARM->>'delay_max' AS delay_max FROM alarmdata2;

我认为根据这些链接(herehere)查询语法很好但是我收到此错误

  

提示:没有运算符匹配给定的名称和参数类型。您   可能需要添加显式类型转换。

我一直在寻找一段时间,但我还没有发现。 有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您必须将ALARM列定义为JSON或JSONB类型:

CREATE TABLE ALARMDATA2(ALARM JSONB)

然后它会起作用。

答案 1 :(得分:1)

解决问题

ALTER TABLE alarmdata2
ALTER COLUMN alarm
  TYPE jsonb
  USING alarm::jsonb;

或者,解决它

SELECT ALARM::jsonb->>'delay_max' AS delay_max
FROM alarmdata2;