[英]Ordering json structure using json_build_object and json_build_array in Postgresql
I am trying to recreate this json using json_build_object and json_build_array in postgresql 我正在尝试在PostgreSQL中使用json_build_object和json_build_array重新创建此json
Here is my desired output: 这是我想要的输出:
[
{
"name": "Albert",
"Gender": "Male",
"tags": [
"Student",
"Geography"
]
}
]
Here is my query: 这是我的查询:
SELECT
json_build_array(json_build_object(
'tags',jsonb_build_array('Student','Geography'),
'Gender','Male',
'name', 'name'
))
FROM student_list
But when I run this query I get the Gender part appearing first and not like my desired output. 但是,当我运行此查询时,我首先看到“性别”部分,而不是所需的输出。
Here is the output I get after running my query 这是运行查询后得到的输出
[
{
"Gender": "Male",
"name": "Albert",
"tags": [
"Student",
"Geography"
]
}
]
What can I do to get it like my desired output and why is not following the order in my query. 我该怎么做才能获得所需的输出,为什么不遵循查询中的顺序。 I tried to rearrange the statements in the query but I noticed that the Gender always will pop first and not like my desired output. 我试图重新排列查询中的语句,但我注意到性别总是会首先弹出,而不是我想要的输出。
Can someone tell me what I am doing wrong. 有人可以告诉我我在做什么错。
https://www.json.org/ https://www.json.org/
An object is an unordered set of name/value pairs. 对象是名称/值对的无序集合。 An object begins with { (left brace) and ends with } (right brace). 对象以{(左括号)开始,以}(右括号)结束。 Each name is followed by : (colon) and the name/value pairs are separated by , (comma). 每个名称后跟有:(冒号),名称/值对之间以,(逗号)分隔。
so you can't expect order in object - only in array 所以你不能期望对象中的顺序-仅在数组中
of course you can always treat json as text and order it with some awful clutch, like having {"b":1,"c":4,"a":"foo"}
: 当然,您始终可以将json视为文本,并使用一些糟糕的命令对其进行排序,例如使用{"b":1,"c":4,"a":"foo"}
:
t=# with c(j) as (values('{"b":1,"c":4,"a":"foo"}'::json))
, p as (select json_object_keys(j) k, j->json_object_keys(j) v from c)
, r as (select '{'||string_agg('"'||k||'":'||v,',') over (order by k desc) ||'}' jsn from p)
select jsn from r order by length(jsn) desc limit 1;
jsn
-------------------------
{"c":4,"b":1,"a":"foo"}
(1 row)
ordered descending and : 有序降序和:
t=# with c(j) as (values('{"b":1,"c":4,"a":"foo"}'::json))
, p as (select json_object_keys(j) k, j->json_object_keys(j) v from c)
, r as (select '{'||string_agg('"'||k||'":'||v,',') over (order by k asc) ||'}' jsn from p)
select jsn from r order by length(jsn) desc limit 1;
jsn
-------------------------
{"a":"foo","b":1,"c":4}
(1 row)
ascending... 上升...
but as soon as you cast it to json, the order in object looses sence... 但是一旦将其转换为json,对象中的顺序就会失去意义...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.