Import JSON to Database

Asked

Viewed 1,562 times

2

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

  • I did this with JS by creating the Sqlite insertion query: https://answall.com/a/236529/64969

2 answers

2

Starting with version 9.2 of Postgressql the type was introduced JSON, that supports data storage and manipulation in JSON format.

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

Filing cabinet 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 );

Recovers all countries using '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'

Recovers all the Spanish-speaking countries':

SELECT
    json.data->>'nome' AS nome
FROM
    (SELECT json_array_elements(info) AS data FROM tb_pais) AS json
WHERE
    json.data->>'lingua' = 'Espanhol';
  • I tried running the command: INSERT INTO tb_pais VALUES (1, pg_read_file('C: Program Files Postgresql 9.6 data models.json')::JSON); But it returned the error: ERROR: input invalid syntax for type json DETAIL: Token "" is invalid. CONTEXT: JSON data, line 1: ... ********* Error ********* ERROR: invalid input syntax for type json SQL state: 22P02 Detail: Token "" is invalid. Context: JSON data, line 1: ...

  • The JSON content is well formed ?

  • I took the same example you did.

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.