1

I am trying to recreate this json using json_build_object and json_build_array in postgresql

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.

0

1 Answer 1

2

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"}:

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.