我只是尝试读取 PostgreSQL 数据库中的 .JSON 文件,但无法读取。我是用 .csv 文件做的,但用 .JSON 文件,我做不到。
.JSON 文件如下所示:
{"s":"S1","p":"P1","j":"J1","qty":200}
{"s":"S1","p":"P1","j":"J4","qty":700}
{"s":"S2","p":"P3","j":"J1","qty":400}
{"s":"S2","p":"P3","j":"J2","qty":200}
这是我尝试的代码,我先创建了表,然后将文件中的数据复制到数据库中。
create table notifies(
s varchar(999),
p varchar(999),
j varchar(999),
qty varchar(999)
);
copy public.notifies(s,p,j,qty)
from 'C:\temp\spj.json';
答案 0 :(得分:1)
您可以将您的这个 json 文件导入一个临时表,然后从那里填充表 CREATE TABLE tmp (c text);
。例如:
创建一个 tmp 表..
tmp
.. 使用 COPY
..
mydb=# \copy tmp from 'C:\temp\spj.json'
notifies
... 最后填充表 INSERT INTO notifies
SELECT q.* FROM tmp, json_to_record(c::json) AS q
(s text, p text, j text, qty int);
SELECT * FROM notifies;
s | p | j | qty
----+----+----+-----
S1 | P1 | J1 | 200
S1 | P1 | J4 | 700
S2 | P3 | J1 | 400
S2 | P3 | J2 | 200
(4 Zeilen)
:
tmp
之后您可能想要删除表 DROP TABLE tmp;
json_populate_record
EDIT:正如@Jeremy 所建议的那样,一个非常优雅的替代方法是使用 INSERT INTO notifies
SELECT q.* FROM tmp, json_populate_record(null::notifies, c::json) AS q;
SELECT * FROM notifies ;
s | p | j | qty
----+----+----+-----
S1 | P1 | J1 | 200
S1 | P1 | J4 | 700
S2 | P3 | J1 | 400
S2 | P3 | J2 | 200
(4 Zeilen)
。谢谢!请参阅下面的评论。
sql.Identifier