1

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.

1 Answer 1

2

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.

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

2 Comments

Thank you. I forgotten to use -> in this case
glad to help you @jedema

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.