Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres export column value not surrounded by doublequote

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    {
        "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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading