从输出中删除jsonb_build_object

3
我正在使用PostgreSQL中的jsonb_build_object创建一个jsonb对象。问题是它在输出中添加了jsonb_build_object列。请参考下面的截图和查询:

enter image description here

     select  jsonb_build_object(
                    'country_name', country_name,
                    'country_code', country_code,
                    'currency_code', currency_code
                )
     from table

有没有办法在输出中排除jsonb_build_object?

请编辑您的问题,包括您正在使用的查询。这样可以帮助我们为您提供解决问题的方案。 - undefined
这是您(未透露)客户程序做出的格式决策。 - undefined
3个回答

1
正如@jjanes所指出的那样,这不是PostgreSQL在做这件事,而是您的客户端应用程序或库将查询结果获取到一个json结构中,在其中将列/字段名作为顶级键注入,以便能够容纳多个列在一个结构中。
您没有指定您希望如何调用保存该函数输出的字段,所以PostgreSQL只是根据函数的名称命名它,因此有了jsonb_build_object的顶级键,但根据数据库来看,它是字段/列名,而不是结果的内部部分。您可以在这里看到它在数据库中的样子:demo
create table your_table as select 
  'Canada' as country_name, 
  'CA' as country_code, 
  'CAD' as currency_code;

select  jsonb_build_object(
                    'country_name', country_name,
                    'country_code', country_code,
                    'currency_code', currency_code
                )
from your_table;
jsonb_build_object
{"country_code": "CA", "country_name": "Canada", "currency_code": "CAD"}

请注意,这是在标题中,而不是实际字段中。要去掉它,您需要在您的客户端/应用程序中去除它。如果您更新问题以指定您使用的客户端/库+语言,并显示您如何获取这些记录,将会很有帮助。


我正在使用Python将查询结果保存为JSON。 - undefined
如果你一个一个地获取它们,那么result=result['jsonb_build_object']将会剥离掉顶层。演示。请记得在添加更多细节时编辑问题 - 如果你把额外信息放在单独的评论中,其他人会更难跟踪。 - undefined
成功了。谢谢。 - undefined

-1
尝试使用CTE(通用表达式)来实现所需的输出。
以下是CTE代码;
WITH cte AS (
    SELECT jsonb_build_object(
        'country_name', country_name,
        'country_code', country_code,
        'currency_code', currency_code
    ) AS jsonb_data
    FROM table
)
SELECT jsonb_data
FROM cte;

现在,'jsonb_build_object'已从输出中排除。

输出仍将包含jsonb_data。 - undefined

-1
试试这个:
with temp_data as (
  select  jsonb_build_object(
                    'country_name', country_name,
                    'country_code', country_code,
                    'currency_code', currency_code
                )
     from table
)

select t->'jsonb_build_object' from temp_data t

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接