postgresql-将数据从JSON文件追加到表 [英] postgresql - Appending data from JSON file to a table

查看:799
本文介绍了postgresql-将数据从JSON文件追加到表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以虹膜数据集中的两列为例-sepal_length和sepal_width。

I am using two columns from the iris dataset as an example - sepal_length and sepal_width.

我有两个表

创建表格虹膜(sepal_length实数,sepal_width实数);

创建表raw_json(data jsonb);

在JSON文件中,我有这样的数据

And inside the JSON file I have data like this

[{ sepal_width:3.5, sepal_length:5.1},{ sepal_width:3.0, sepal_length:4.9}]

我要做的第一件事是从'/data.json'复制raw_json;

到目前为止,我只能弄清楚如何使用 jsonb_array_elements

So far I have only been able to figure out how to use jsonb_array_elements.

从raw_json中选择jsonb_array_elements(data); 退还

           jsonb_array_elements            
-------------------------------------------
 {"sepal_width": 3.5, "sepal_length": 5.1}
 {"sepal_width": 3.0, "sepal_length": 4.9}

我是nt将 raw_json 表中的数据插入(实际上附加)到 iris 表中。我发现我需要使用 jsonb_to_recordset json_populate_recordset 。但是如何?

I want to insert (append actually) the data from raw_json table into iris table. I have figured out that I need to use either jsonb_to_recordset or json_populate_recordset. But how?

还可以在没有 raw_json 表的情况下完成此操作吗?

Also, could this be done without the raw_json table?

PS-几乎所有现有的SE问题在其查询中都使用原始json字符串。所以这对我不起作用。

PS - Almost all the existing SE questions use a raw json string inside their queries. So that didn't work for me.

推荐答案

您必须从 jsonb_array_elements的输出中提取json。 用于 from 子句

INSERT INTO iris(sepal_length,sepal_width)
select (j->>'sepal_length' ) ::real,
       (j->>'sepal_width'  ) ::real
from raw_json cross join jsonb_array_elements(data) as j;

演示

这篇关于postgresql-将数据从JSON文件追加到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆