简体   繁体   English

是否可以即时将文本列转换为 json,然后在 postgres 中对其进行查询?

[英]Is it possible to convert text column to json on the fly then query against it in postgres?

I have to work with a text column, but its content is json format.我必须使用文本列,但其内容是 json 格式。 An example:一个例子:

{"company":"company name","entityName":"entity name","asOfDate":1604725200000}

Right now, I am using LIKE to get the results I want:现在,我正在使用 LIKE 来获得我想要的结果:

select distinct a.company_name from company_table a
where a.json_field LIKE '%' || ?1 || '%'

I would like to be able to query the json directly:我希望能够直接查询 json:

select distinct a.company_name from company_table a
where a.json_field ->> company = ?1

A third option would be getting all the rows, then use code to parse through them, I'm fairly certain that the growth of table is low and won't reach like 10k/year.第三种选择是获取所有行,然后使用代码解析它们,我很确定表的增长很低,不会达到 10k/年。

While the LIKE method works, I don't know if it's 100% correct.虽然 LIKE 方法有效,但我不知道它是否 100% 正确。

Any suggestions?有什么建议?

Just cast it:只需cast它:

where (a.json_field::jsonb) ->> company = ?1

This will error if your string is not valid JSON.如果您的字符串不是有效的 JSON,这将出错。

I would recommend fixing your schema, and convert that column to JSON once and for all, so you don't need to worry about this anymore.我建议修复您的架构,并将该列一劳永逸地转换为 JSON,这样您就不必再担心了。 You can do this in a single statement:您可以在单个语句中执行此操作:

alter table company_table 
    alter column json_field type jsonb 
    using json_field::jsonb;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM