2016-08-30 196 views
4

比如我有一個文件customers.json這是一個對象(嚴格的形成)的數組,這是很普通的(沒有嵌套對象)這樣的(什麼是重要的:它已經包括IDS):如何將JSON文件導入PostgreSQL?

[ 
    { 
    "id": 23635, 
    "name": "Jerry Green", 
    "comment": "Imported from facebook." 
    }, 
    { 
    "id": 23636, 
    "name": "John Wayne", 
    "comment": "Imported from facebook." 
    } 
] 

我想要將它們全部導入到我的postgres數據庫中,並放入表customers

我發現了一些非常困難的方法,當我應該將它作爲json-typed列導入到像imported_json這樣的表和列名爲data的列中,然後使用sql來獲取這些值並將其插入到真實表中。

但是,有沒有簡單的方法導入JSON到Postgres沒有觸及SQL?

+0

」*沒有觸及sql *「否。與說SQL的關係數據庫進行交互的唯一方式就是SQL。 –

+0

@a_horse_with_no_name哦...我很確定,然後我可以簡單地將我的JSON轉換爲SQL查詢。我會研究:) –

回答

13

您可以將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 p 
on conflict (id) do update 
    set name = excluded.name, 
     comment = excluded.comment; 

的新客戶將被插入,現有的將被更新。 「魔術」部分是生成JSON對象的關係表示的json_populate_recordset(null::customer, doc)


以上假設表定義是這樣的:

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

如果數據爲文件提供的,你需要首先把該文件到一些數據庫中的表。例如:

create unlogged table customer_import (doc json); 

然後將文件上傳到該表的單個行中,例如,在psql使用\copy命令(或任何你的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 p 
on conflict (id) do update 
    set name = excluded.name, 
     comment = excluded.comment; 
+0

我感謝你的幫助,但我發現我更好地將我的JSON轉換爲SQL(在我的情況下是紅寶石)。然後只需使用psql命令導入sql。這比用sql解析json對象更容易:) Btw thx。 –

3

原來有一種簡單的方法可以使用命令行psql工具將多行JSON對象導入到postgres數據庫的JSON列中,而無需將JSON明確嵌入到SQL語句中。該技術記錄在postgresql docs中,但它有點隱藏。

訣竅是使用反引號將JSON加載到psql變量中。例如,給定一個/tmp/test中的多行JSON文件。JSON如:

{ 
    "dog": "cat", 
    "frog": "frat" 
} 

我們可以使用下面的SQL將其加載到一個臨時表:

# \set content `cat /tmp/test.json` 
# create temp table t (j jsonb); 
# insert into t values (:'content'); 
# select * from t; 

其給出結果:

   j     
──────────────────────────────── 
{"dog": "cat", "frog": "frat"} 
(1 row) 

您還可以執行的操作直接在數據上:

# select :'content'::jsonb -> 'dog'; 
?column? 
────────── 
"cat" 
(1 row) 

下面這個只是在SQL中嵌入JSON,但讓psql自己執行插值更加簡單。 「

+1

^這是黃金。只需在不到5分鐘的時間內將26000條記錄導入我的數據庫。沒有一個步驟花了超過一秒鐘。 – fgblomqvist