Postgres 从 JSON 对象中选择字段的子集

JK.*_*JK. 6 postgresql json

给定一些具有多个字段的 JSON 对象,例如

{a: 1, b: true, c: "some string", d: {foo: "bar"}}
Run Code Online (Sandbox Code Playgroud)

您如何选择其中一些字段作为新的 JSON 对象?

我知道您可以选择一个字段:

select data->>'a' from '{a: 1, b: true, c: "some string", d: {foo: "bar"}}' as data
Run Code Online (Sandbox Code Playgroud)

但是如何将多个字段选择到一个新的 JSON 对象中呢?我如何选择 justab

select (what?) from '{a: 1, b: true, c: "some string", d: {foo: "bar"}}' as data
Run Code Online (Sandbox Code Playgroud)

结果将是:

{a: 1, b: true}
Run Code Online (Sandbox Code Playgroud)

我正在使用 9.6 和一个普通的 JSON 列

Ram*_*cov 0

您可以使用 PostgreSQLjsonb_each函数将 JSON 数据转换为键/值记录。此外,您还可以使用jsonb_typeof函数来获取 JSON 元素的类型。例如:

select jsonb_typeof(t1.pval) as ptype, t1.pkey, t1.pval 
from jsonb_each('{"a": 1, "b": true, "c": "some string", "d": {"foo": "bar"}}'::jsonb) t1 (pkey, pval)
Run Code Online (Sandbox Code Playgroud)

结果:

p型 p_key p_val
数字 A 1
布尔值 真的
细绳 C “一些字符串”
目的 d {“foo”:“酒吧”}