如何在postgresql中将json对象作为列?

fh_*_*ash 11 postgresql json

我在mu PostgreSQL 9.05上有这些表:

表:core 字段:name,description,data

data field是一个json字段,有(例如): {"id": "100", "tax": "4,5"}

one每个数据始终是json.

我的问题是:我可以将所有JSON字段作为查询字段吗?像这样返回:name, description, id, tax....

问题是:我的JSON确实有各种字段,可以是Id,税或其他.

a_h*_*ame 15

你不能"动态地"做到这一点.您需要指定要拥有的列:

select name, description, id, 
       data ->> 'tax' as tax,
       data ->> 'other_attribute' as other_attribute
from core;
Run Code Online (Sandbox Code Playgroud)

如果你做了很多,你可能想把它放到一个视图中.


另一种选择是在Postgres中创建一个表示JSON中属性的对象类型,例如

create type core_type as (id integer, tax numeric, price numeric, code varchar);
Run Code Online (Sandbox Code Playgroud)

然后,您可以将JSON强制转换为该类型,并且JSON中的相应属性将自动转换为列:

使用上面的类型和以下JSON:{"id": "100", "tax": "4.5", "price": "10", "code": "YXCV"}你可以这样做:

select id, (json_populate_record(null::core_type, data)).*
from core;
Run Code Online (Sandbox Code Playgroud)

它将返回:

id | tax  | price | code
---+------+-------+-----
 1 | 4.50 |    10 | YXCV
Run Code Online (Sandbox Code Playgroud)

但是您需要确保每个JSON值可以转换为相应对象字段的类型.

如果更改对象类型,则将自动更新使用它的任何查询.因此,您可以通过中央定义管理您感兴趣的列.


Tam*_*lyn 9

从PostgreSQL 9.4开始,您还可以使用json_to_record

从JSON对象构建任意记录(请参见下面的注释)。与所有返回记录的函数一样,调用者必须使用AS子句显式定义记录的结构。

例如:

select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}') as x(a int, b text, d text)
Run Code Online (Sandbox Code Playgroud)

退货

 a |    b    | d
---+---------+---
 1 | [1,2,3] |
Run Code Online (Sandbox Code Playgroud)