4

I have a json column on my database pgsql enter image description here

I need to search keys with localId, I tried both this query:

SELECT *
FROM public.translations
    where datas->>'localId' = 7;

enter image description here and

 SELECT *
    FROM public.translations
        where datas->>'localId'::text = '7';

no results.

How can i do it please?

when i make this query i have no values

SELECT datas->>'localId' as local
FROM public.translations 
SELECT datas::json->>'localId' as local
FROM public.translations 

enter image description here

1
  • Sample data is better presented as formatted text. See here for some tips on how to create nice looking tables. Commented Apr 8, 2021 at 13:08

3 Answers 3

7

Your screenshot is a bit hard to read, but it seems your JSON is in fact a JSON array, so you need to pick the first element from there:

where (datas -> 0 ->> 'localId')::int = 7

or a bit shorter:

where (datas #>> '{0,localId}')::int = 7

alternatively you can use the contains operator @> to check if there is at least one element with localId = 7. But the @> operator requires jsonb, not json, so you will need to cast your column

where datas::jsonb @> '[{"localId": 7}]'

Online example

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

6 Comments

Thanks, It's ok when i have only one element in the array but when i have 2 elements and the second element is with value 7 it's not fetched
@user1428798: the @> will do that
@ a_horse_with_no_name when i try it i have this error : "ERROR: operator does not exist: json @> unknown LINE 1: SELECT * FROM public.translations WHERE datas @> '[{"localI... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. SQL state: 42883 Character: 48"
@user1428798: I overlooked that you are using a json column rather than the recommended jsonb. See my edit, you will have to cast the column
Thanks very helpful it's ok now !
|
2

What you need is ::json right after datas :

SELECT *
FROM public.translations
where datas::json->>'localId' = '7';

Related question on StackOverFlow

If you need more informations here is the Newest Postgresql Documentation

Comments

0

you need to cast both values to the same type

where datas->>'localId' = '7'::text;

or

where (datas->>'localId')::integer = 7;

or you should add brackets to you example

where (datas->>'localId')::text = '7';

2 Comments

'7'::text can be simplified to '7' and (datas->>'localId')::text can be simplified to datas->>'localId' - the ->> operator already returns a text value
same i tried (datas->>'localId')::integer = 7; but no results

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.