I have a Postgres table Id, Description, OtherStuff. Want to export all my data as JSON but want to format Description as json object too.
For example I have :
| ID | Description | OtherStuff |
| :----------------------------------- |
| 1 | My Description| |
| 2 | Desc 2 | |
I want to export to
[
{
"Id" : 1,
"Description" : { "Fr": "My Description", "En" : ""},
"OtherStuff" : ""
},
{
"Id" : 2,
"Description" : { "Fr": "Desc 2", "En" : ""},
"OtherStuff" : ""
}
]
Currently the data i exported as
"Description" : "{ \"Fr\": \"My Description\", \"En\" : \"\"}",
.... // removed extra stuff for shortness
"Description" : "{ \"Fr\": \"Desc 2\", \"En\" : \"\"}",,
I already came up with that query
SELECT t.uuid as "Id",
FORMAT('{ "Fr" : "%s", "En: "" }',t.description) as "Description",
t.othercolumn as "Otherstuff"
FROM MyTable t
What can I do to not surround the value with double quotes?
>Solution :
Use json (or jsonb) functions to create json. No text function can do this correctly, and you have to rebuild the existing json functions to get something comparable.
SELECT json_agg( -- creates a json array
JSON_BUILD_OBJECT( -- creates a json object
-- key, value
'Id', id
, 'Description', description
, 'Otherstuff', COALESCE(otherstuff, '')
)
)
FROM t1;
By the way, I would strongly advise to never ever use UPPER case in your table, column, or other database object names. You keep on escaping these names because PostgreSQL only looks for the lower case names by default. Waist of time writing all the quotes ". And kind of ugly as well