Keyboard Maestro's %JSONValue% token provides (amongst other things) keyed access to any item you want, from a large set of values.
(Like Prompt with List, but without the need for UI interaction)
Data often arrives, however, as multiple lines of text, with each key and value delimited by a single character like a tab (%Tab%
\t
) or comma, or a multi-character delimiter like "__"
.
Here is a subroutine which constructs a JSON dictionary (readable by the %JSONValue%
token) from a list of delimited lines.
JSONFromDelimitedLines.kmmacros (7,0 Ko)
An example of its use might be the following:
The ValuePrecedesKey
option defaults to false / no / 0
if you leave it blank, and allows for cases where you want to search by keys in the 2nd column for values in the 1st column.
The default assumption is Key__Value
(rather than Value__Key
).
To choose that reversed option, you can supply any (case-insensitive) string drawn from true|yes|1
Expand disclosure triangle to view JS source of subroutine
const main = () => {
const
keyValueReversed = confirms(
kmvar.local_ValuePrecedesKey
);
return JSON.stringify(
lines(kmvar.local_Source)
.reduce(
(dict, row) => {
const
[key, value] = row.split(
kmvar.local_Delimiter
),
update = keyValueReversed
? { [value]: key }
: { [key]: value };
return Object.assign(dict, update);
},
{}
),
null, 2
);
};
// ----------------------- GENERIC -----------------------
// confirms :: String -> Bool
const confirms = v => {
const s = v || "";
return isNaN(s)
? ["Y", "T"].includes(s.toLocaleUpperCase()[0])
: 0 < Number(s);
};
// lines :: String -> [String]
const lines = s =>
// A list of strings derived from a single string
// which is delimited by \n or by \r\n or \r.
0 < s.length
? s.split(/\r\n|\n|\r/u)
: [];
// MAIN ---
return main();