我需要获取以下 JSON 对象作为输出:
"{"table" : "test", "column 1" : {"pos" : 1, "name" : "col1", "type" : "integer"},
"column 2" : {"pos" : 2, "name" : "col2", "type" : "date"}}"
当我使用
build_json_object('table','test', 'column 1', build_json_object('pos',1,'name','col1','type','integer'), 'column 2', build_json_object('pos',2,'name','col2','type','date'));
它抛出一个错误: 错误:函数 build_json_object(未知,整数,未知,未知,未知,未知)不存在
当我使用
build_json_object('table','test', 'column 1',('pos',1,'name','col1','type','integer'), 'column 2', ('pos',2,'name','col2','type','date'));
它只会产生错误的结果:
"{"table" : "test", "column 1" : {"f1":"pos", "f2": 1, "f3":"name", "f4": "col1", "f5":"type", "f6": "integer"},
"column 2" : {"f1":"pos", "f2": 2, "f3":"name", "f4": "col2", "f5":"type", "f6": "date"}}"
如何使用 build_json_object 函数生成嵌套的 JSON 对象?
最佳答案
提示 - 从嵌套最多的对象开始逐步构建表达式。使用适当的缩进。请注意,表达式在某种程度上类似于结果。
(我用 jsonb_pretty()
包装了主表达式以获得漂亮的输出):
select
jsonb_pretty(
json_build_object(
'table', 'test',
'column 1', json_build_object('pos', 1, 'name', 'col1', 'type', 'integer'),
'column 2', json_build_object('pos', 2, 'name', 'col2', 'type', 'date')
)::jsonb
);
jsonb_pretty
---------------------------
{ +
"table": "test", +
"column 1": { +
"pos": 1, +
"name": "col1", +
"type": "integer"+
}, +
"column 2": { +
"pos": 2, +
"name": "col2", +
"type": "date" +
} +
}
(1 row)
关于json - 嵌套 JSON 的 build_json_object 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38361613/