将json数据从文件加载到Postgres

ani*_*nil 9 postgresql json

我需要将多个JSON文件中的数据加载到Postgres表中,每个JSON文件中都有多个记录.我使用以下代码,但它不起作用(我在Windows上使用pgAdmin III)

COPY tbl_staging_eventlog1 ("EId", "Category", "Mac", "Path", "ID")
from 'C:\\SAMPLE.JSON' 
delimiter ','
;
Run Code Online (Sandbox Code Playgroud)

SAMPLE.JSON文件的内容是这样的(给出了许多这样的记录):

[{"EId":"104111","Category":"(0)","Mac":"ABV","Path":"C:\\Program Files (x86)\\Google","ID":"System.Byte[]"},{"EId":"104110","Category":"(0)","Mac":"BVC","Path":"C:\\Program Files (x86)\\Google","ID":"System.Byte[]"}]
Run Code Online (Sandbox Code Playgroud)

Chr*_*ian 23

试试这个:

BEGIN;
-- let's create a temp table to bulk data into
create temporary table temp_json (values text) on commit drop;
copy temp_json from 'C:\SAMPLE.JSON';

-- uncomment the line above to insert records into your table
-- insert into tbl_staging_eventlog1 ("EId", "Category", "Mac", "Path", "ID") 

select values->>'EId' as EId,
       values->>'Category' as Category,
       values->>'Mac' as Mac,
       values->>'Path' as Path,
       values->>'ID' as ID      
from   (
           select json_array_elements(replace(values,'\','\\')::json) as values 
           from   temp_json
       ) a; 
COMMIT;
Run Code Online (Sandbox Code Playgroud)

  • @JoshuaRobinson:你必须在一个事务中运行整个脚本.您可能正在将其作为"脚本"运行,并且当它运行"select"子句时,临时表已被删除(在提交时丢弃). (2认同)