0
votes

how can i create a json file from a postgresql table "test4json" with sql query:

column1 column2 column3
name 1 0 10
name 2 0 10
name 3 0 10

a single json file in one row...withot CRLF such this:

{"name 1": {"column2": 0,"column3": 10},"name 2": {"column2": 0,"column3": 10},"name 3":{"column2": 0,"column3": 10}}

for the values column 1 i dont't need the name of the column !

and how can i create from the result a test4json.json file in a directory c:\test4json ?

Origin Table is

name x y width height pixelRatio sdf
S1R1 0 0 20 10 1 false
S1R2 0 10 20 10 1 false
S1R3 0 20 20 10 1 false
S1R4 0 30 20 10 1 false
S1R5 0 40 20 10 1 false

thx

2
It's usually recommended to use arrays for tabular data. - Bergi
It's really unclear what you are asking for. You already have successfully created a json text representing your table. Now put it into a file and save it. What exactly is the problem? - Bergi
Ah, I had missed the [postgresql] tag on the question. Are you saying you don't have a HTML table, but an arbitrary database table, and want to convert that to json? Have a look at dba.stackexchange.com/q/90482/188406 - Bergi
i have the tabe in postgresql, i want to create the json file from the postgresql table with a query - Tibor
Please post your table definition (and sample data, if necessary) as SQL. Also show us what you tried and how the existing Q&As didn't help - Bergi

2 Answers

2
votes

You can use jsonb_object_agg() for this:

select jsonb_object_agg(column1, to_jsonb(t) - 'column1')
from the_table t;

Online example

How you save that as a JSON file depends completely on the SQL client you are using. In psql you could use the \o ("output to") meta command

0
votes

copy (select jsonb_object_agg(column1, to_jsonb(t) - 'column1') from the_table t) to 'c:\test4json\test4json.json'; works for the output as a json file