Skip to content

Instantly share code, notes, and snippets.

@westc
Last active February 19, 2022 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/2842b2a58f698c277e283388275a8d8e to your computer and use it in GitHub Desktop.
Save westc/2842b2a58f698c277e283388275a8d8e to your computer and use it in GitHub Desktop.
jsonToApexInserts() - Makes it easy to take the JSON that comes from the Salesforce Bulk Data Loader and turn it into Apex that can run in the Developer Console.
function jsonToApexInserts(json, objectName='SObject') {
const list = JSON.parse(json).map(function(row) {
return `\tnew ${objectName}(\n`
+ Object.keys(row).map(function(key) {
return `\t\t${key} = `
+ JSON.stringify(row[key]).replace(
/"([^]*)"/,
function(_, inner) {
// If this is a date string or a datetime string as specified here
// https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_valid_date_formats.htm
// turn the values into the appropriate Apex type.
var m = /^(\d{4})-(\d\d)-(\d\d)([T ]\d\d:\d\d:\d\d(?:.\d{3}(?:Z|[\+\-]\d\d:\d\d)?)?)?$/.exec(inner);
if (m) {
var d = +new Date(inner);
if (d === d) {
if (m[4]) {
return "DateTime.newInstance(Long.valueOf('" + d + "')) /* " + inner + " */";
}
return 'Date.newInstance(' + [+m[1], +m[2], +m[3]].join(',') + ') /* ' + inner + ' */';
}
}
return "'" + inner.replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
}
);
}).join(',\n') + '\n\t)';
}).join(',\n');
return [
`List<${objectName}> tList = new List<${objectName}> {`,
`${list}`,
`};`,
`insert tList;`,
`System.debug(JSON.serializePretty(tList));`,
`delete tList;`
].join('\n');
}
{
// Name of the function that takes the input string and produces the output string.
"transform": "jsonToApexInserts",
// Where to find the code that will be eval'd.
"files": ["jsonToApexInserts.js"],
// Add options
"params": [
{
"label": "Object Name",
"name": "objectName",
"value": "SObject",
"type": "text"
}
],
// Input setup
"input": { "label": "Input (JSON)", "language": "json" },
// Output setup
"output": { "label": "Output (Apex)", "language": "apex" },
// Type of IO App
"type": "split"
}
@westc
Copy link
Author

westc commented Feb 17, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment