I'm trying to understand the way the Postgresql
is dealing with JSON
. I've declared a two-columns table and I'd like to create a new View to get some boolean values.
So far, I've been able to get the value as text but what I'd like to get is whether the field is defined or not.
For example, if the JSON
has the key frameMenuData.frameElement
, it should print has_frame
to true.
SELECT
customer_data->>'frameMenuData'->>'frameElement' AS has_frame,
FROM
simple_list
WHERE
TRUE
AND guid='AAAA';
The above code gives me the content of that row. I need to know if customer_data->>'frameMenuData'->>'frameElement'
is defined or not.
How could I achieve that ?
Thanks for your help.
In Postgres, if you select a key that does not exist it will return null. so u can check the existence of a key by checking the null value of that key.
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.
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.
One simple difference between JSON and jsonb data type is that JSON stores the exact copy of the data represented/ inputted in the JSON format to the user whereas jsonb stores the data in the binary format which means that the input data is first processed and then stored in the binary form.
Problem solved. It was barely easy.
SELECT (customer_data->>'frameMenuData'->>'frameElement' IS NULL) AS has_frame,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With