Here is a little JSON helper to create (escaped) JSON Strings from AppelScript records.
-- Toggle BTTShowHUD example
property isVisible : 0
if isVisible = 0 then
set isVisible to 1
else
set isVisible to 0
end if
set jsonData to {BTTTriggerConfig:{BTTHUDText:"Button clicked", BTTShowHUD:isVisible}}
set jsonString to my Serialize(jsonData)
tell application "BetterTouchTool"
update_trigger "FACFB1C3-3459-4765-BD7F-1A8B93977A30" json jsonString
end tell
-- JSON helper
on Serialize(theData)
script theScript
use framework "Foundation"
property parent : a reference to current application
property NSJSONWritingPrettyPrinted : a reference to 1
on toJSON(theData)
set theJSONData to parent's NSJSONSerialization's dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted |error|:(missing value)
set theString to (parent's NSString's alloc()'s initWithData:theJSONData encoding:(parent's NSUTF8StringEncoding)) as text
return theString
end toJSON
end script
return theScript's toJSON(theData)
end Serialize
If you want to create AppleScript records from JSON strings you can use this handler:
set jsonString to "{\"BTTTriggerConfig\" : {\"BTTHUDText\" : \"Button clicked\",\"BTTShowHUD\" : 1}}"
set jsonData to my Deserialize(jsonString)
-- JSON helper
on Deserialize(strJSON)
script theScript
use framework "Foundation"
property parent : a reference to current application
property NSJSONWritingPrettyPrinted : a reference to 1
on fromJSON(strJSON)
set {x, e} to parent's NSJSONSerialization's JSONObjectWithData:((parent's NSString's stringWithString:strJSON)'s dataUsingEncoding:(parent's NSUTF8StringEncoding)) options:0 |error|:(reference)
if x is missing value then
error e's localizedDescription() as text
else
return item 1 of ((parent's NSArray's arrayWithObject:x) as list)
end if
end fromJSON
end script
return theScript's fromJSON(strJSON)
end Deserialize
Tip: If the script cannot be compiled, insert the line:
use scripting additions
at the beginning of the script.