3

Given this query:-

SELECT id as id,
       attributes->>'name' as file_name, 
       status 
from workflow.events 
where schema='customer' 
  and type='FILE_UPLOAD'

id,file_name, status
1,name,status
2,name2,status2

I want to output this structure:-

{
 "1" :{"id" :"1", "file_name" : "name", "status" : "status1"},
 "2" :{"id" :"2", "file_name" : "name2","status" : "status2"}
}

I can do it at the moment using string functions but this seems messy and inefficient. CAn it be done using the native postgresql json functions?

2

1 Answer 1

4

If you want to get two records with json, use row_to_json() function:

with cte as (
    select 
        id as id,
        attributes->>'name' as file_name, 
        status 
     from workflow.events 
     where schema='customer' and type='FILE_UPLOAD'
)
select row_to_json(c) from cte as c

output:

{"id":1,"file_name":"name","status":"status"}
{"id":2,"file_name":"name2","status":"status2"}

If you want to get json array:

with cte as (
    select 
        id as id,
        attributes->>'name' as file_name, 
        status 
     from workflow.events 
     where schema='customer' and type='FILE_UPLOAD'
)
select json_agg(c) from cte as c

output:

[{"id":1,"file_name":"name","status":"status"}, 
 {"id":2,"file_name":"name2","status":"status2"}]

But for you desired output, I can only suggest string transformation:

with cte as (
    select 
        id::text as id,
        file_name, 
        status 
    from workflow.events 
    where schema='customer' and type='FILE_UPLOAD'
)
select ('{' || string_agg('"' || id || '":' || row_to_json(c), ',') || '}')::json from cte as c

sql fiddle demo

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

3 Comments

The final step with concatenation, that should be good enough after row_to_json() did most of the work. I'll delete my answer since you undeleted yours, and your answer is is good.
Thanks @ErwinBrandstetter, I see that PostgreSQL have json_each to fetch data from json structured like this output, but seems it don't have function to do it other way around as OP wants :(
There is very little of examples about those functionalities with JSON in postgres 9.3, this answer is enlightening! Thanks Roman

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.