0

I have a table, for example writing in psql. This table has a column json (text type). It contains text like this:

writing:[{"variableName":variableValue ...}]

variableValues are different types, including text ,bigint and date.

I want to get all rows from writing where variableName has the value 2.

I'm using this select:

select * from writing where json::json->>'variableName' = '2' limit 5

This select returns me 0 rows, but there are a lot of data in this table, which should pass this condition. Any idea what is wrong, or maybe you have better statement.

Im using limit 5 because need just 5 rows.

2
  • 1
    Unrelated, but: JSON data is best stored in a column defined as jsonb, not as text. Then you would notice that writing:[{"variableName":variableValue ...}] is not a valid JSON value. Commented Apr 4, 2019 at 7:52
  • Noticed that but data structure is far beyond so changing that will be way too time consuming. Anyway I appreciate the tip. Commented Apr 4, 2019 at 7:58

1 Answer 1

1

You'll have to prepend a { and append a } to make it a JSON like you intend. As it is, it will become a single JSON string.

Then you'll have to access the attribute as

('{' || json || '}')::json->'writing'->1->>'variableName'
Sign up to request clarification or add additional context in comments.

4 Comments

With Your example it pop out that argument of WHERE must be type boolean, not type text because as u said it will become a single JSON string.
Right. Your condition would then be WHERE /* my expression */ = '2'.
Ye. Now everything is working as it should. Much thanks for help. Have one question for your statement what exactly is doing 1 in 'writing'->1->>'variableName'
It gets the first element of a JSON array (the [...]).

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.