json - 如何从 Postgres 中的 json 中选择查询

标签 json postgresql

我在 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"}

最佳答案

您可以使用横向连接和 json_to_recordset 将 json 数组扩展为一组记录。然后,您可以在生成的记录中过滤 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'

Demo on 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        |
| :------------------------- |
| {"description": "fr text"} |

关于json - 如何从 Postgres 中的 json 中选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468417/

相关文章:

android - 为什么我不能从 json Retrofit 中获取特殊字段?

windows - 编码=ASCII;和编码= UNICODE;不要在 Npgsql 3 连接字符串中工作

postgresql - 使用主键和外键构建树

postgresql - 无法在ubuntu中安装postgres

postgresql - 通过 aws 网络平衡器负载平衡 postgres 实例可能吗?

Python如何迭代嵌套json中的所有键和值以放入csv文件中

json - ASP.NET Core 3 - Serilog 如何在 appsettings.json 文件中配置 Serilog.Sinks.Map?

java - JsonDeserializer不适用于该类,而仅适用于该类的单个元素

javascript - 使用表单输入在 $.ajax() 方法中设置 var?

带有伪行的 json_agg()