Postgres array_to_string(),在JSONB字段中包含数组

时间:2018-03-23 14:17:06

标签: sql json postgresql

我想在JSONB字段中获取数组的TEXT。我期望的字符串如下:

dom1.com,  dom2.com,  dom3.com

JSONB字段包含:

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

我尝试使用以下代码来使用array_to_string()函数:

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

但它返回错误

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.

我也试试这个

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;

但它返回错误

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 个答案:

答案 0 :(得分:1)

在这种情况下,您必须使用->运算符(返回值为json)和正确的函数键入jsonb_array_elements

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;

更多信息here