How popular is a postgres table with JSON?

1

I'd like to populate my tables with Json. But I can not. Does anyone have a solution?

Follow JSON: link

    
asked by anonymous 16.05.2018 / 01:25

1 answer

1

Assuming the data destination table is something like:

CREATE TABLE tb_foobar
(
    id BIGINT primary key,
    name TEXT
);

You can use the json_populate_record() function of Postgres to insert the data in your table from a given data in JSON format, see:

INSERT INTO tb_foobar( id, name )
(SELECT * FROM json_populate_record( NULL::tb_foobar, '{"id": 100, "name": "JOAO"}'));

INSERT INTO tb_foobar( id, name )
(SELECT * FROM json_populate_record( NULL::tb_foobar, '{"id": 200, "name": "MARIA"}'));

INSERT INTO tb_foobar( id, name )
(SELECT * FROM json_populate_record( NULL::tb_foobar, '{"id": 300, "name": "JESUS"}'));

INSERT INTO tb_foobar( id, name )
(SELECT * FROM json_populate_record( NULL::tb_foobar, '{"id": 400, "name": "MADALENA"}'));

Consulting:

SELECT id, nome FROM tb_foobar; 

Output:

|  id |     name |
|-----|----------|
| 100 |     JOAO |
| 200 |    MARIA |
| 300 |    JESUS |
| 400 | MADALENA |

SQLFiddle: link

EDIT:

In your case, the JSON fault file has multiple records. You can use the json_populate_recordset() function combined with WITH to solve your problem .

Assuming you have a table similar to this:

CREATE TABLE tb_estados_cidades
(
    id BIGSERIAL primary key,
    sigla VARCHAR(2),
    nome TEXT
);

You can implement something like:

WITH arquivo_json( doc ) AS (
VALUES (
'[
    { "sigla": "AC", "nome": "Acre" },
    { "sigla": "AL", "nome": "Alagoas" },
    { "sigla": "AM", "nome": "Amazonas" },
    { "sigla": "AP", "nome": "Amapá" }
  ]'::json))


INSERT INTO  tb_estados_cidades ( sigla, nome )
  SELECT
    rec.sigla, rec.nome
  FROM
    arquivo_json AS arq
  CROSS JOIN 
     json_populate_recordset( NULL::tb_estados_cidades, doc ) AS rec;

Inquiry:

SELECT id, sigla, nome FROM tb_estados_cidades;

Output:

| id | sigla |     nome |
|----|-------|----------|
|  1 |    AC |     Acre |
|  2 |    AL |  Alagoas |
|  3 |    AM | Amazonas |
|  4 |    AP |    Amapá |

SQLFiddle: link

    
16.05.2018 / 19:25