首页 > 解决方案 > 如何在 Postgres 中从 json 中选择查询

问题描述

我在hotel_data这样的字段中有 JSON 数据:

{ 
   "title":"foo",
   "description":[ 
      { 
         "locale":"pt",
         "content":"pt text"
      },
      { 
         "locale":"fr",
         "content":"fr text"
      }
   ]
}

我想description只选择fr描述。可以使用 Postgres 以及如何使用?

我正在尝试使用->>,但它不起作用......

SELECT  
    hotel_data->'description'->>'locale' = 'fr' AS description
FROM hotel LIMIT 1;

注意:我不想使用SELECT *...

异常输出:{description: "fr text"}

标签: jsonpostgresql

解决方案


您可以使用横向连接并将json_to_recordsetjson 数组扩展为一组记录。然后,您可以过滤locale生成记录中的列,最后用您预期的结果重构一个新的 json 对象:

select json_build_object('description', d.content) hotel_data_descr_fr
from 
    mytable,
    json_to_recordset(hotel_data->'description') as d("locale" text, "content" text)
where d.locale = 'fr'

DB Fiddle 上的演示

with mytable as (
    select '{ 
   "title":"foo",
   "description":[ 
      { 
         "locale":"pt",
         "content":"pt text"
      },
      { 
         "locale":"fr",
         "content":"fr text"
      }
   ]
}'::json hotel_data
)
select json_build_object('description', d.content) hotel_data_descr_fr
from 
    mytable,
    json_to_recordset(hotel_data->'description') as d("locale" text, "content" text)
where d.locale = 'fr'
| hotel_data_descr_fr |
| :------------------------- |
| {“描述”:“fr 文本”} |

推荐阅读