Skip to content

Instantly share code, notes, and snippets.

@foureyedraven
Last active February 21, 2019 21:41
Show Gist options
  • Save foureyedraven/ca90a7dcbfd0918c153b0c91ec9317c5 to your computer and use it in GitHub Desktop.
Save foureyedraven/ca90a7dcbfd0918c153b0c91ec9317c5 to your computer and use it in GitHub Desktop.
Use nodeJS to insert values into existing PostgreSQL table from JSON file
const { Client } = require('pg')
const fs = require('fs')
const local_file = require('./your_json_data.json')
class Postgres {
constructor() {
this.client = new Client({
user: 'postgres',
host: 'xx.xxx.xxx.xx',
database: 'postgres',
password: 'password',
port: xxxx,
})
this.client.connect()
}
async query(sql) {
try {
const { rows } = await this.client.query(sql)
return rows
} catch (err) {
throw err
}
}
}
async function run() {
const postgres = new Postgres()
const makeVal = (val)=>{
if(val === undefined) {
return "NULL"
} else {
return "'" + JSON.stringify(val).replace(/'/g, "''") + "'"
}
}
const makeVals = (objs) => {
return objs.map((obj) => makeVal(obj)).join(',')
}
for(let k of Object.keys(local_file)) {
try {
const query = `INSERT INTO your_table (
id,
title,
category,
author,
published_at,
images,
)
VALUES(` + makeVals([
k,
local_file[k].title,
local_file[k].type,
local_file[k].author,
local_file[k].publishedAt,
local_file[k].attachments.images,
]) + ')'
console.log(query)
postgres.query(query)
} catch(err) {
throw err
}
}
}
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment