0

PostgreSQL has a lot of functions for working with JSON data. However, it seems to be difficult to import JSON data, since the COPY command does not support JSON.

Assuming I have a file named data.json that contains JSON data like the following:

[
  {"id":1, "name": "Jakob"},
  {"id":2, "name": "Klara"}
]

Is there a simple way to import that JSON data file just using psql?

1
  • If it's a one time project, I would use a JSON to CSV converter, then use the copy command per normal. stackoverflow.com/questions/4130849/… Commented Feb 26, 2017 at 14:15

1 Answer 1

1

You can use the CSV format to import arbitry data, as long as you quote it correctly. You can use cat & sed to quote your CSV file:

cat data.json | sed 's/"/""/g' | cat <(echo '"') - <(echo '"')

The first cat command reads the file, the sed command replaces all double quotes with two double quotes, and the final cat puts a double quote before and after the json.

Let's create a table on the server:

psql -c 'CREATE TABLE import(data jsonb)'

You can now use the result of this command with psql:

cat data.json | sed 's/"/""/g' | cat <(echo '"') - <(echo '"') | \
 psql -c 'COPY import(data) FROM STDIN (FORMAT CSV)'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.