Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL Nested JSON Querying

On PostgreSQL 9.3.4, I have a JSON type column called "person" and the data stored in it is in the format {dogs: [{breed: <>, name: <>}, {breed: <>, name: <>}]}. I want to retrieve the breed of dog at index 0. Here are the two queries I ran:

Doesn't work

db=> select person->'dogs'->>0->'breed' from people where id = 77; ERROR:  operator does not exist: text -> unknown LINE 1: select person->'dogs'->>0->'bree...                                  ^ HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts. 

Works

select (person->'dogs'->>0)::json->'breed' from es_config_app_solutiondraft where id = 77;  ?column? -----------  "westie" (1 row) 

Why is the type casting necessary? Isn't it inefficient? Am I doing something wrong or is this necessary for postgres JSON support?

like image 940
ravishi Avatar asked Jul 24 '14 21:07

ravishi


People also ask

How do I query JSON data in PostgreSQL?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

Does Postgres support JSON?

PostgreSQL offers two types for storing JSON data: json and jsonb . To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14. 7. The json and jsonb data types accept almost identical sets of values as input.


1 Answers

This is because operator ->> gets JSON array element as text. You need a cast to convert its result back to JSON.

You can eliminate this redundant cast by using operator ->:

select person->'dogs'->0->'breed' from people where id = 77; 
like image 167
max taldykin Avatar answered Sep 18 '22 07:09

max taldykin