0

I'm trying to retreive some specific data from a json stored in my database.

Here is my fidle : https://www.db-fiddle.com/f/5qZhsyddqJNej2NGj1x1hi/1

An exemple of a json string :

{
   "complexProperties":[
      {
         "properties":{
            "key":"Registred",
            "Value":"123456789"
         }
      },
      {
         "properties":{
            "key":"Urgency",
            "Value":"Total"
         }
      },
      {
         "properties":{
            "key":"ImpactScope",
            "Value":"All"
         }
      }
   ]
}

In this case I need to retreive the value of Registred which is 123456789

Here is the request I tried to retreive first all value:

SELECT CAST(data AS jsonb)::json->>'complexProperties'->'properties' AS Registred FROM jsontesting

Query Error: error: operator does not exist: text -> unknown

3
  • 1
    The first error is that you are storing JSON in a text column. That column should be defined as jsonb Commented Sep 26, 2022 at 11:35
  • The second error is that you store it in a JSON to begin with. The third error is that you don't store it as {"Registered": 123456789}. Commented Sep 26, 2022 at 11:38
  • It's from a proprietary software, I don't have hands on it Commented Sep 26, 2022 at 11:39

2 Answers 2

1

You can use a JSON Path expression:

select jsonb_path_query_first(data, '$.complexProperties[*].properties ? (@.key == "Registred").Value')
from jsontesting;

This returns a jsonb value. If you need to convert that to a text value, use jsonb_path_query_first(...) #>> '{}'

Online example

Sign up to request clarification or add additional context in comments.

2 Comments

Needed to add CAST(data AS jsonb) because my column is as VARCHAR
@executable: yes, annoying casts are required if you don't use the proper data type when defining the table.
1

An alternative that first flattens the JSON field (the arrj subquery) and then performs an old-school select. Using your jsontesting table -

select (j -> 'properties' ->> 'Value') 
from 
(
 select json_array_elements(data::json -> 'complexProperties') as j 
 from jsontesting
) as arrj
where j -> 'properties' ->> 'key' = 'Registred';

Online example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.