0

Assume i have a table called MyTable and this table have a JSON type column called myjson and this column have next value as a json array hold multiple objects, for example like next:

[
  {
    "budgetType": "CF",
    "financeNumber": 1236547,
    "budget": 1000000
  },
  {
    "budgetType": "ENVELOPE",
    "financeNumber": 1236888,
    "budget": 2000000
  }
]

So how i can search if the record has any JSON objects inside its JSON array with financeNumber=1236547

4
  • This link provide json operator you can use: postgresql.org/docs/9.3/functions-json.html Commented Mar 8, 2022 at 23:10
  • @MeyssamToluie the link you provided is to an EOL version of Postgres. Furthermore there have been a lot of additions to the JSON functions and a whole new JSON type JSONB added along with functions for the new type. The appropriate link is JSON(B) Functions. Commented Mar 8, 2022 at 23:26
  • Are you using the json or jsonb type? Commented Mar 8, 2022 at 23:41
  • i am using JSON type, but i can't find the function which i can use to filter out the property inside the objects of the array, that's why i wrote the question here. i hope any one can suggest any solution. Commented Mar 8, 2022 at 23:44

2 Answers 2

2

Something like this:

SELECT
    t.*
FROM
    "MyTable",
    LATERAL json_to_recordset(myjson) AS t ("budgetType" varchar,
        "financeNumber" int,
        budget varchar)
WHERE
    "financeNumber" = 1236547;

Obviously not tested on your data, but it should provide a starting point.

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

1 Comment

FYI, if you use the jsonb type you get to use the SQL/JSON Path Language.
0
with a as(
 SELECT  json_array_elements(myjson)->'financeNumber'  as col   FROM mytable)
select exists(select from a where col::text = '1236547'::text );

https://www.postgresql.org/docs/current/functions-json.html
json_array_elements return setof json, so you need cast.
Check if a row exists: Fastest check if row exists in PostgreSQL

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.