栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将JSON文件导入PostgreSQL?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将JSON文件导入PostgreSQL?

您可以将JSON输入到SQL语句中,以提取信息并将其插入表中。如果JSON属性的名称与表列的名称完全相同,则可以执行以下操作:

with customer_json (doc) as (   values     ('[      {        "id": 23635,        "name": "Jerry Green",        "comment": "imported from facebook."      },      {        "id": 23636,        "name": "John Wayne",        "comment": "imported from facebook."      }    ]'::json))insert into customer (id, name, comment)select p.*from customer_json l  cross join lateral json_populate_recordset(null::customer, doc) as pon conflict (id) do update   set name = excluded.name,       comment = excluded.comment;

将插入新客户,将更新现有客户。“魔术”部分是,

json_populate_recordset(null::customer,doc)
它生成JSON对象的关系表示。


上面假设一个表定义是这样的:

create table customer (  id        integer primary key,  name      text not null,  comment   text);

如果数据以文件形式提供,则需要首先将该文件放入数据库中的某个表中。像这样:

create unlogged table customer_import (doc json);

然后将文件上传到该表的单行中,例如使用中的

copy
命令
psql
(或SQL客户端提供的任何命令):

copy customer_import from 'customers.json' ....

然后,您可以使用上面的语句,只需删除CTE并使用登台表:

insert into customer (id, name, comment)select p.*from customer_import l  cross join lateral json_populate_recordset(null::customer, doc) as pon conflict (id) do update   set name = excluded.name,       comment = excluded.comment;


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/375434.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号