【问题标题】:How to import a JSON file into postgresql databse?如何将 JSON 文件导入 postgresql 数据库?
【发布时间】:2021-02-10 15:04:55
【问题描述】:

我刚刚尝试在我的 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';

【问题讨论】:

  • COPY 无法“读取”json,只需将单行插入单列即可。
  • 那么,如何从 .json 文件中插入一列?
  • 没有时间给出完整的答案。见JSON functions。例如:select * from json_to_record('{"s":"S1","p":"P1","j":"J1","qty":200}') as t(s varchar, p varchar, j varchar, qty integer); s | p | j | qty ----+----+----+----- S1 | P1 | J1 | 200

标签: sql json postgresql


【解决方案1】:

您可以将您的这个 json 文件导入到一个临时表中,然后从那里填充表 notifies。例如:

创建一个 tmp 表..

CREATE TABLE tmp (c text);

.. 使用COPY 将您的 json 文件导入表 tmp ..

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;

编辑:正如@Jeremy 所建议的那样,使用json_populate_record 是一个非常优雅的替代方案。谢谢!请参阅下面的 cmets。

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)

【讨论】:

  • 请注意,您可以使用json_populate_record(null::notifies, c::json),而不是json_to_record(c::json) AS q (s text, p text, j text, qty int)。重用通知类型更容易。
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 2018-05-02
  • 2017-01-06
  • 2019-10-05
  • 1970-01-01
  • 2018-01-23
  • 1970-01-01
  • 2014-12-06
相关资源
最近更新 更多