Last active
February 19, 2022 03:10
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
// 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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is the corresponding IO App:
https://yourjs.com/gist-io/2842b2a58f698c277e283388275a8d8e