[英]How to convert JSON data into table and store into Postgres DB using Node JS?
I need help in converting json data into datatable and store inside postgresql DB. 我需要帮助将json数据转换为数据表并存储在postgresql DB中。
For example, 例如,
[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]
I'd like to convert the above data or lets say store the data as a table with rows and columns. 我想转换上面的数据,或者说将数据存储为包含行和列的表。
I think we do have a datatype called "json" but it's to store the entire json right? 我想我们确实有一个名为“json”的数据类型,但它是存储整个json的吗? But I want to convert as real table what we see in DB, like below,
但我想将我们在DB中看到的真实表格转换成如下所示,
name | role
--------------+-------
"abc" | "swe"
"xyz" | "Tester
Could you please help me how to parse them please? 你能帮我解决一下如何解析它们吗? I'm using Node JS.
我正在使用Node JS。
Any pointers will be helpful. 任何指针都会有所帮助。 Thanks a lot for your time.
非常感谢你的时间。
I think it will work, convert your json into object and prepare and insert it using npm package node-postgres(np)
and node-sql(sql || sql string builder for node)
, Take reference from the following the code. 我认为它会工作,将你的json转换为对象,并使用npm包
node-postgres(np)
和node-sql(sql || sql string builder for node)
准备和插入它,参考以下代码。
const pg = require('pg');
const sql = require('sql');
let usersToInsert = JSON.parse(`[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]`);
let User = sql.define({
name: 'users',
columns: [
'name',
'role'
]
});
async function run() {
let client;
try {
client = new pg.Client({
connectionString: 'postgresql://localhost/node_example'
});
await client.connect();
let query = User.insert(usersToInsert).toQuery();
console.log(query);
let {rows} = await client.query(query);
console.log(rows);
} catch (e) {
console.error(e);
} finally {
client.end();
}
}
run();
May be something like you need ? 可能是你需要的东西?
select jsonb_array_elements(j)->>'name' as name, jsonb_array_elements(j)->>'role' as role
from (
select '[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]'::jsonb as j
) t
If so, You can simply do INSERT INTO .. SELECT
for saving data into table 如果是这样,您只需执行
INSERT INTO .. SELECT
将数据保存到表中
demo: https://rextester.com/LIV68809 演示: https : //rextester.com/LIV68809
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.