Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using \COPY to load CSV with JSON fields into Postgres

I'm attempting to load TSV data from a file into a Postgres table using the \COPY command.

Here's an example data row:

2017-11-22 23:00:00     "{\"id\":123,\"class\":101,\"level\":3}"

Here's the psql command I'm using:

\COPY bogus.test_table (timestamp, sample_json) FROM '/local/file.txt' DELIMITER E'\t'

Here's the error I'm receiving:

ERROR:  invalid input syntax for type json
DETAIL:  Token "sample_json" is invalid.
CONTEXT:  JSON data, line 1: "{"sample_json...
COPY test_table, line 1, column sample_json: ""{\"id\":123,\"class\":101,\"level\":3}""

I verified the JSON is in the correct JSON format and read a couple similar questions, but I'm still not sure what's going on here. An explanation would be awesome

like image 449
lemon master Avatar asked Nov 16 '17 22:11

lemon master


People also ask

Should I use JSON or Jsonb Postgres?

In general, most applications should prefer to store JSON data as jsonb , unless there are quite specialized needs, such as legacy assumptions about ordering of object keys. RFC 7159 specifies that JSON strings should be encoded in UTF8.

How do I import a CSV file into a table in PgAdmin 4?

To import CSV using this PgAdmin Import CSV method, you have to do the following: Click on the Tools tab at the top of your PgAdmin Home Page. Select the Query Tool in the drop-down menu that appears. Enter the title and columns in your CSV file as an SQL Query.


2 Answers

To load your data file as it is:

\COPY bogus.test_table (timestamp, sample_json) FROM '/local/file.txt' CSV DELIMITER E'\t' QUOTE '"' ESCAPE '\'
like image 144
Abelisto Avatar answered Sep 16 '22 16:09

Abelisto


Your json is quoted. It shouldn't have surrounding " characters, and the " characters surrounding the field names shouldn't be escaped.

It should look like this:

2017-11-22 23:00:00 {"id":123,"class":101,"level":3}
like image 20
teppic Avatar answered Sep 20 '22 16:09

teppic