I think this will get you there. Let me know if not, or if I misunderstood.
var kmResults = {};
kmResults.Value1 = "My Value 1";
kmResults.Error = "My Error";
return JSON.stringify(kmResults);
// ==================================================
var kme = Application("Keyboard Maestro Engine");
var kmResults = JSON.parse(kme.getvariable("kmResults"));
setKMVariablesFromObject(null, kmResults, "zzz")
function setKMVariablesFromObject(kme, obj, prefix) {
kme = kme || Application("Keyboard Maestro Engine");
prefix = prefix || "";
Object.keys(obj).forEach(function(key) {
kme.setvariable(prefix + key, { to: obj[key] });
});
}
Here’s a little bit of an explanation. I know I won’t have all the technical terms right, but the logic is correct:
var kmResults = {};
kmResults.Value1 = "My Value 1";
kmResults.Error = "My Error";
“kmResults” is an Object Literal. In it’s simplest form, it’s a set of key/value pairs. Actually, all JS objects are just key/value pairs.
Let’s look at the JSON string for the above code:
{
"Value1": "My Value 1",
"Error": "My Error"
}
See? key:value.
As such, you can reference object properties in a couple of ways:
kmResults.Value1 = "My Value 1";
kmResults["Error"] = "My Error";
If you use the second method, object property names can contain spaces and other characters.
So, if you want to walk through all the properties of an object, you can use
Object.keys(obj)
to get an array of the property names, e.g. keys.
Then you can use the keys to access the object’s properties, like this (or using a “for”, or whatever):
Object.keys(obj).forEach(function(key) {
console.log("'" + key + "': '" + obj[key] + "'");
});