【问题标题】:Can't append json array into a json array in postgresql function无法将 json 数组附加到 postgresql 函数中的 json 数组中
【发布时间】:2021-12-31 03:06:29
【问题描述】:

我正在尝试将 json 数组或对象附加到 json 数组中,但 array_append 总是将 json 作为字符串插入。

我的结果是;

{"{"category_id":8,"category_name":"08 Candy","is_active":true,"category_name_app":"Candy","display_order":7}"}

但我希望它是这样的。所以我可以在我的代码中对它们进行 json_decode。

[{"category_id":8,"category_name":"08 Candy","is_active":true,"category_name_app":"Candy","display_order":7}]

这是我的功能逻辑

    for all_categories in select * from categories where is_active = '1' loop
            show_at_homepage = 0;
        
            for current_subcat in select * from public."V_category_to_sub_category_w_names" where category_id = all_categories.category_id and sub_category_is_active = '1' loop
                
                
                select * into product_count from public."V_APP_products_w_sub_categories" where sub_category_id = current_subcat.sub_category_id and store_id = get_store_id and is_deleted='0';
                if count(product_count) > 0 then
                    
                    show_at_homepage = 1;
                                
                
                end if;
                
            end loop;
            
            if show_at_homepage = 1 then
                    select row_to_json(all_categories) into cat_json;
                    
                    select array_append(my_json_result_array,cat_json) into my_json_result_array;
                end if;
        
        
    end loop;
    return my_json_result_array;

【问题讨论】:

    标签: arrays json postgresql stored-procedures


    【解决方案1】:

    您可以将array_append 应用于任何类型的postgres 数据类型数组,包括json[],但不能将其应用于json 类型的json 数组。在您的情况下,您需要应用 json 函数和运算符,请参阅 manual,更具体地说是 json_build_array 函数:

    替换

    select array_append(my_json_result_array,cat_json) into my_json_result_array
    

    select json_build_array(my_json_result_array,cat_json) into my_json_result_array
    

    或者当您使用jsonb 而不是json 这是manual 推荐:

    select jsonb_build_array(my_json_result_array,cat_json) into my_json_result_array
    

    【讨论】:

    • 这很好,但我想将此 jsonb 数组作为数组附加到 my_json_result_array 中。我做不到。当我使用 array_append 时,它会将 cat_json 作为字符串附加到 my_json_result_array_array 中。所以即使它显示像数组这样的括号,它也会用双引号将它包裹起来并变成一个字符串。
    • 好的,看看更新后的答案,告诉我它是否符合您的需要。
    • 这很接近但是当我 jsonb_build_array 它插入到数组之外。让我解释。我想要的是这样的[//这里将附加类别作为数组],但是使用 json_build_array,它给了我像 [[{category1}],category2]。我必须将它附加到与 category1 相同的数组中
    • 根据您的最后评论,我回到最初的答案:SELECT '[]' :: jsonb || my_json_result_array :: jsonb || cat_json :: jsonb 将返回 [my_json_result_array , cat_json] :: jsonb。如果这不能回答您的问题,请提供完整的数据样本:my_json_result_array、cat_json 以及拼接后的预期结果。
    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多