Writing JSON data with NSJSONSerialization
As a bookend to my previous post on reading JSON data with NSJSONSerialization, here is a snippet of code demonstrating how to write an AppleScript record as JSON data. While my sample converts an AppleScript record to JSON, the same technique can be used with AppleScript lists as well.
Here is the AppleScript code:
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
use framework "Foundation"
-- classes, constants, and enums used
property NSJSONWritingPrettyPrinted : a reference to 1
property NSJSONSerialization : a reference to current application's NSJSONSerialization
-- An AppleScript data structure to convert to JSON
set theData to {|menu|:¬
{|id|:"file", value:"File", popup:¬
{menuitem:{¬
{value:"New", onclick:"CreateNewDoc()"}, ¬
{value:"Open", onclick:"OpenDoc()"}, ¬
{value:"Close", onclick:"CloseDoc()"}}}}}
-- Ask for the file to write to
set theFile to choose file name
set theJSONData to NSJSONSerialization's dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted |error|:(missing value)
theJSONData's writeToFile:(theFile's POSIX path) atomically:false
The result looks like this:
{
"menu" : {
"id" : "file",
"value" : "File",
"popup" : {
"menuitem" : [
{
"value" : "New",
"onclick" : "CreateNewDoc()"
},
{
"value" : "Open",
"onclick" : "OpenDoc()"
},
{
"value" : "Close",
"onclick" : "CloseDoc()"
}
]
}
}
}
NOTE: the NSJSONWritingPrettyPrinted
value passed to the NSJSONSerialization's dataWithJSONObject
command causes the resulting JSON text to be pretty printed. If you want all the whitespace removed, pass 0:
set theJSONData to NSJSONSerialization's dataWithJSONObject:theData options:0 |error|:(missing value)
This results in the following output:
{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}
Write JSON Data.scpt.zip (6.0 KB)