sql - How to import a JSON file into postgresql databse?
问题描述
I just tried to read a .JSON file in my PostgreSQL database but it is not able to read it. I did it with a .csv file, but with a .JSON file, I am not able to do it.
This is how the .JSON file looks like:
{"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}
This is the code that I tried, I created the table first and then copy the data from the file into the database.
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';
解决方案
您可以将您的这个 json 文件导入到一个临时表中,然后从那里填充该表notifies
。例如:
创建一个 tmp 表..
CREATE TABLE tmp (c text);
tmp
..使用COPY
..将您的 json 文件导入表中
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
:正如@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)
推荐阅读
- laravel - 如何散列最后一个插入ID并设置到请求中然后保存到laravel中的db中。?
- javascript - 我在 javascript 中遇到 DOM 的问题
- scala - 如何在 Play 中获取原始请求正文?
- android - Google Play 64 位要求 Gamemaker Studio
- javascript - 角度如何使用查询列表对象?
- java - 在控制台中使用在 Eclipse 中创建的包运行代码
- javascript - 如何获得此加载屏幕效果
- java - 如何实现一种以异步方式处理服务超时的方法?
- runtime - 如何在运行时设置 Phaser 3 游戏的背景颜色?
- dependency-injection - 无法解析类型 Microsoft 扩展配置 IConfiguration 的服务