Skip to content

Instantly share code, notes, and snippets.

@kevinfelisilda
Last active May 9, 2020 02:35
Show Gist options
  • Save kevinfelisilda/f54c83f61af171c71afaba900b77c381 to your computer and use it in GitHub Desktop.
Save kevinfelisilda/f54c83f61af171c71afaba900b77c381 to your computer and use it in GitHub Desktop.
Convert JSON array data to SQL insert statement
/**
* This function only get attributes from the first item
* if not specified from the 3rd parameter
*/
function json_array_to_sql_insert(table_name, arr, _attributes) {
if (!Array.isArray(arr) || arr.length === 0){
throw new Error('Enter an array with atleast 1 item');
}
const attributes = _attributes || Object.keys(arr[0]);
let sql = `INSERT INTO \`${table_name}\` (${attributes.map(a => `\`${a}\``).join(', ')})\nVALUES`;
arr.forEach(function(item) {
const row = [];
attributes.forEach(function(field) {
const cell = item[field] || null;
row.push('string' === typeof cell ? cell.replace('\'','\\\'') : cell);
});
sql += `\n(${row.map(r => r === null ? 'NULL' :`'${r}'`).join(', ')})`;
});
return sql;
}
const json_data = [
{ id: 1, email: '[email protected]', meta: '{"admin":true}' },
{ id: 2, email: '[email protected]' }
];
json_array_to_sql_insert('table', json_data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment