Passing complex data between KM actions using JSON

Using the JSON.stringify() function (in Javascript for Applications) lets us place complex data structures in single KM variables, and pass them from one action to another.

(for example if we have a set of reader actions – reading perhaps OPML, MD, FTML and other outline formats, and a separate set of writer actions, writing out outlines in these formats, we can pass the parsed 'tree' from a Reader action to a Writer action as a JSON-encoded Javascript object).

Encode a Javascript object as a JSON string, and save it in a KM variable:

var dct = {
	id:1, txt:"alpha", nest:[
		{id:2, txt:"leaf"},
		{id:3, txt:"flower"},
		{id:4, txt:"fruit"}
	]
};

JSON.stringify(dct);

and then use the object directly in the Javascript code of another action:

osascript -l JavaScript <<JXA_END 

	($KMVAR_treeJSON).nest[2];

JXA_END

demo - passing Javascript objects between actions.kmmacros (2.1 KB)

2 Likes

Here, for example, is the JSON string contents of a KM variable keeping track of named and focal groups of applications which I use for windowing and workspace macros:

{
  "thinking": [
    "Atom",
    "DEVONthink Pro",
    "iThoughtsX"
  ],
  "writing": [
    "Atom",
    "Marked 2"
  ],
  "scripting": [
    "Atom",
    "Script Debugger",
    "Script Editor",
    "iTerm"
  ],
  "coding": [
    "Atom",
    "Chrome",
    "Dash",
    "iTerm"
  ],
  "grazing": [
    "Mail",
    "ReadKit",
    "Safari",
    "Tweetbot"
  ],
  "plain text drafting": [
    "FoldingText",
    "Marked 2"
  ],
  "focal": [
    "Atom",
    "Chrome",
    "Dash",
    "iTerm"
  ],
  "atom-find-fold-mark": [
    "Atom",
    "Finder",
    "FoldingText",
    "Marked 2"
  ],
  "code": [
    "CodeRunner"
  ]
}