Import JSON to Database

2

I have a json file, and would like to import it into a database. Is there any way to automate this process? There is no database preference, but if it had some function for PostgreSQL it would be better.

    
asked by anonymous 28.09.2017 / 16:19

2 answers

2

As of version 9.2 of PostgresSQL, the type JSON was introduced, which supports the storage and manipulation of data in JSON format.

You can use the pg_read_file() function to read text files stored in data_directory of the server in order to automate data import.

File paises.json :

[
    { "nome": "Brasil",    "lingua": "Portugues", "moeda": "Real"  },
    { "nome": "Portugal",  "lingua": "Portugues", "moeda": "Euro"  },
    { "nome": "Argentina", "lingua": "Espanhol",  "moeda": "Peso Argentino"  },
    { "nome": "Mexico",    "lingua": "Espanhol",  "moeda": "Peso Mexicano"  },
    { "nome": "Franca",    "lingua": "Frances",   "moeda": "Euro"  },
    { "nome": "Alemana",   "lingua": "Alemao",    "moeda": "Euro"  },
    { "nome": "EUA",       "lingua": "Ingles",    "moeda": "Dolar"  }
]

Data structure:

CREATE TABLE tb_pais
(
    cod INTEGER,
    info JSON
);

Importing JSON file:

INSERT INTO tb_pais VALUES ( 1, pg_read_file('/var/lib/pgsql/data/paises.json')::JSON );

Retrieve all countries that use 'Euro' as currency:

SELECT
    json.data->>'nome'
FROM
    (SELECT json_array_elements(info) AS data FROM tb_pais) AS json
WHERE
    json.data->>'moeda' = 'Euro'

Retrieves all the countries that speak 'Spanish':

SELECT
    json.data->>'nome' AS nome
FROM
    (SELECT json_array_elements(info) AS data FROM tb_pais) AS json
WHERE
    json.data->>'lingua' = 'Espanhol';
    
28.09.2017 / 21:22
1

In the sql server you can import, I do not know what's your "automatically" (when put in a folder? when receiving an email? when calling a function?). But in this link explains several ways how to import json into sql server

link

    
28.09.2017 / 16:41