Reading JSON data with NSJSONSerialization

how-to
foundation
asobjc
json

(Mark Alldritt) #1

Here’s a snippet of code demonstrating how to read JSON data and convert it into an AppleScript record.

Here is a sample JSON file (test.json):

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

And here is the AppleScript code to read it:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
use framework "Foundation"

-- classes, constants, and enums used
property NSJSONSerialization : a reference to current application's NSJSONSerialization
property NSData : a reference to current application's NSData

set theFile to choose file

set theJSONData to NSData's dataWithContentsOfFile:(theFile's POSIX path)
set theJSON to NSJSONSerialization's JSONObjectWithData:theJSONData options:0 |error|:(missing value)

theJSON as record

--> {
--	|menu|:{
--		|id|:"file", 
--		value:"File", 
--		popup:{
--			menuitem:{
--				{
--					value:"New", 
--					onclick:"CreateNewDoc()"
--				}, 
--				{
--					value:"Open", 
--					onclick:"OpenDoc()"
--				}, 
--				{
--					value:"Close", 
--					onclick:"CloseDoc()"
--				}
--			}
--		}
--	}
--}

Read JSON Data.zip (241.9 KB)