简体   繁体   中英

Query Json data saved in Postgres

I'm trying to query JSON data saved in postgres. This is how the table is created

CREATE TABLE ALARMDATA2(ALARM        CHAR(1300))

This is the JSON object:

{"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}

I'd like to query based on "delay_max" (the first entry in JSON). I am using this query

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

I think the query syntax is fine as per these links ( here and here ) but I am getting this error

HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.

I've been searching for a while but I have not clue. Any suggestions why ?

You must define the ALARM colum as type JSON or JSONB:

CREATE TABLE ALARMDATA2(ALARM JSONB)

And then it will work.

Fix the problem

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

Or, work around it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM