0

I have this query which works perfectly fine. Here, "data" is a jsonb column in "info" table.

select data from info where data @> '{"last_name": "Pinkman"}';

Now, I have to pass this particular query in a function as a parameter. Inside the function, I am trying to form a jsonb object by concatenating this query in the following manner but I am getting an error.

CREATE OR REPLACE FUNCTION run_query(query text) RETURNS jsonb AS $$
    DECLARE
        obj text;
    BEGIN
        obj := '{' || '"query"' || ':"' || query || '"}';
        RETURN obj::jsonb;
    END
$$ LANGUAGE plpgsql;
db=# select run_query('select data from info where data @> ''{"last_name": "Pinkman"}''');
ERROR:  invalid input syntax for type json
DETAIL:  Token "last_name" is invalid.
CONTEXT:  JSON data, line 1: ..."select data from info where data @> '{"last_name...
PL/pgSQL function run_query(text) line 6 at RETURN

I know I can use jsonb_build_object() to create the object but I have to create it as a string first and then cast into jsonb. How do I do that? Thx.

2
  • Please edit your question and add the function's code. Commented Jun 5, 2020 at 8:52
  • @a_horse_with_no_name I have edited the question. Please have a look. Thx. Commented Jun 5, 2020 at 9:30

1 Answer 1

1

I know I can use jsonb_build_object() to create the object but I have to create it as a string first

Then do so:

CREATE OR REPLACE FUNCTION run_query(query text) 
  RETURNS jsonb
AS
$$
DECLARE
  obj text;
BEGIN
  obj := jsonb_build_object('query', query)::text;

  ... work with the text ...

  RETURN obj::jsonb; 
END
$$
LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

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.