I want to get a TEXT of an array in JSONB field. The string that I expected are the following :

dom1.com,  dom2.com,  dom3.com

The JSONB field contains that :

{
    "id": 10,
    "domain_list": [
        "dom1.com",
        "dom2.com",
        "dom3.com"
    ]
}

I try to use the array_to_string() function by using the following code :

SELECT
    array_to_string(
        jsonb_array_elements(
            '{"id": 10,"domain_list": [  "dom1.com",  "dom2.com",  "dom3.com"]}'::jsonb->'domain_list'
        ),
        ', '
    );

But it returns the error

ERROR:  function array_to_string(jsonb, text) does not exist
LINE 2:         array_to_string(
                ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

I also try this

SELECT string_agg(domain_list::text, ', ')
FROM json_array_elements(
    '{"id": 10,"domain_list": [  "dom1.com",  "dom2.com",  "dom3.com"]}'::jsonb->>'domain_list'
) as domain_list;

But it returns the error

ERROR:  function json_array_elements(text) does not exist
LINE 2:     FROM json_array_elements(
                 ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
up vote 1 down vote accepted

You must use -> operator (return value as json) and proper function for you type, jsonb_array_elements in this case:

SELECT 
    string_agg(domain_list::text, ', ')
FROM jsonb_array_elements(
    '{"id": 10,"domain_list": [  "dom1.com",  "dom2.com",  "dom3.com"]}'::jsonb->'domain_list'
) as domain_list;

More info here.

  • Thank you. I forgotten to use -> in this case – jedema Mar 23 at 14:38
  • glad to help you @jedema – Michel Milezzi Mar 23 at 14:38

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.