User Tools

Site Tools


dictionary:more:parsejson

Parse JSON

It can be very useful to read JSON data from some source and get that info easily into XTension. The Parse JSON command turns JSON text into nested applescript records or lists. It throws an applescript error if the JSON data doesn’t parse so you should wrap it in a try on error block.

Usage:

parse json [text] the text of the JSON data. Returns either an AppleScript Record if the JSON data was keyed or an AppleScript list if the data was a JSON array.

Examples:

set myJSONData to “{\”unitName\”:\”unitValue\”:37}”


try
  set myRecord to parse json myJSONData
on error
  write log “there was an error parsing the JSON data!” color red
  return
end try

set theUnitName to unitName of myRecord
set theUnitValue to unitValue of myRecord

write log “the value of “ & theUnitName & “ is “ & theUnitValue

or if you have an array it might look something like:

set myJSONData to “[1, 2, 3, 4, 5]”

set myList to parse json myJSONData

repeat with thisValue in myList
  write log thisValue
end repeat

Complex Structures

if you have complex structures those can be sorted out too. If you had JSON data that looked something like this:

[
  {“unitAddress”:42, “newValue”:17},
  {“unitAddress”:43, “newValue”:18},
  {“unitAddress”:44, “newValue”:19}
}

you could loop to get each keyed dictionary and then access each one separately. It would result in an AppleScript list of AppleScript Records.

set myList to parseJson thatDataFromAbove

repeat with thisRecord in myList
  write log “unit at address “ & unitAddress of thisRecord & “ is set to “ & newValue of thisRecord
end repeat

any reasonable number of embedded levels of json arrays or dictionaries are supported for parsing.

Reserved Word Handling

Getting named keys out of an AppleScript record requires that you write the name in plain text before the record object and not put it in quotes.

set myThing to whateverTheKeyIs of theRecord

this works fine as long as whateverTheKeyIs is not a reserved word in AppleScript or a verb in the XTension dictionary. In that case it would refuse to compile. What if your key was “number”? You can’t do a set mything to number of theRecord as thats a reserved word in AppleScript. There is a way to force applescript to treat the term as a key string and not to use it as a language keyword. In that case you put pipe “|” characters around the key.

so if you had json that looked like this:

{ “number”:15, “date”:”7/15/95”}

where both the keys are reserved words you could still get the data out like this:

set myNumber to |number| of myRecord
set myDate to |date| of myRecord
/home/e805485/machomeautomation.com/data/pages/dictionary/more/parsejson.txt · Last modified: 2023/02/13 14:52 by 127.0.0.1