I realize this is blasphemy in this forum, but if you are dealing a lot with JSON strings, have you considered using JavaScript for Automation (JXA) instead of AppleScript?
There are two main issues with using JSON strings in AppleScript:
- Parsing the JSON string into usable data (records usually)
- Ease of use of the results of #1.
Of course, all of this is built-in to core JavaScript, used by JXA. And JXA gives you the same access to Apple Events as AppleScript.
Parsing JSON strings is a very simple, effective, one line, both to parse, and then to convert to string.
//--- Parse JSON String to Create Object ---
var oMenu = JSON.parse(jsonString);
//--- Make Some Changes to oMenu ---
oMenu.MenuName = "Dinner Menu";
//--- Now Create a New JSON String ---
var menuJSONStr = JSON.stringify(oMenu);
//--- LOG Pretty JSON String ---
console.log(JSON.stringify(oMenu, null, 4));
JavaScript’s objects and arrays are much more powerful and easy to use than AppleScript records and lists. We all know how slow and difficult AppleScript records are.
For more info on JavaScript objects, see: JavaScript Objects in Detail
While I am far from a JXA expert, I’ll be glad to help you, or anyone, write (or convert from AppleScript) a JXA script that uses JSON strings.
Here’s the full JXA script. Open in Script Editor and be sure to set the Language to “JavaScript”;
(I had to use the AppleScript code tags since this forum does not provide tags for JavaScript)
//--- JSON String from Nigel's Post ---
var jsonString = `{
\"MenuID\":5,
\"MenuVersion\":1,
\"MenuName\":\"Lunch Menu\",
\"MenuItems\":[
{
\"Name\":\"TUSCANI MEDITERRANEAN CON POLLO\",
\"Description\":\"Pasta\",
\"PKID\":2,
\"ParentID\":1,
\"Ingredients\":[
{
\"PKID\":123,
\"IngName\":\"Cheese\",
\"Included\":true,
\"ExtraPrice\":0
},
{
\"PKID\":124,
\"IngName\":\"Sausage\",
\"Included\":false,
\"ExtraPrice\":0.99
}
],
\"ItemPricing\":[
{
\"PKID\":456,
\"SizeName\":\"Large\",
\"SizePrice\":12.99
},
{
\"PKID\":678,
\"SizeName\":\"Small\",
\"SizePrice\":14.99
}
]
}
]
}`
//--- Parse JSON String into Complex Object ---
var oMenu = JSON.parse(jsonString);
//--- Make Some Changes to oMenu ---
oMenu.MenuName = "Dinner Menu";
//--- Now Create a New JSON String ---
var menuJSONStr = JSON.stringify(oMenu);
//--- LOG Pretty JSON String ---
console.log(JSON.stringify(oMenu, null, 4));