10

I have a field named qn of JSONB type of this form:

[{id: 1, text: 'A'}, {id: 2, text: 'B'}]

To get all the text, I can do:

SELECT jsonb_array_elements(qn)->>'text' from templates where id=1

My question is, how can I merge into a single string like this:

A, B

If the field is not JSONB, it can be done easily using:

SELECT array_to_string(ARRAY(select title from templates), ', ');

How do you do it if the field is JSONB?

2 Answers 2

6

Simply aggregate into a string:

SELECT string_agg(txt, ', ') AS all_text
FROM (
  SELECT jsonb_array_elements(qn)->>'text' AS txt
  FROM templates
  WHERE id = 1) sub;
Sign up to request clarification or add additional context in comments.

1 Comment

Tks, it works on this form. I was actually trying to use it at to_tsvector. setweight(to_tsvector(coalesce(array_to_string(array(jsonb_array_elements(new.questions)->>'text'), ', '), '')), 'D');
0

Sorry, can't comment. Topic starter needed tsvector column. I had such structure for text column named article with json data and needed search text in the key text:

{"time": "some time_structure", "data": {"blocks": [{"data": {"text": "Some long, long text", "image": "image_url"}}, {"data": {"text": "another long text"}}]}}

I generated tsvector field such way:

setweight(to_tsvector('russian'::regconfig, jsonb_path_query_array(article::jsonb, '$.blocks[*].data.text')), 'C')

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.