简体   繁体   中英

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.

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? But I want to convert as real table what we see in DB, like below,

   name   |  role       
--------------+-------
"abc"     | "swe"
"xyz"     | "Tester

Could you please help me how to parse them please? I'm using 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.

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

demo: https://rextester.com/LIV68809

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM