Skip to content

Instantly share code, notes, and snippets.

@ohthreesixtyfive
Last active September 16, 2022 16:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohthreesixtyfive/c563c8df930eb9a375a9d6c112e51a36 to your computer and use it in GitHub Desktop.
Save ohthreesixtyfive/c563c8df930eb9a375a9d6c112e51a36 to your computer and use it in GitHub Desktop.
PowerFx: Parse a provided JSON string to retrieve a list of keys and their values.
// Made with ♥ by @ohthreesixfive
// Output: A two-column collection of keys and values parsed from the provided json string
ClearCollect(
colJsonParseResults,
With(
{jsonString: varYourJSONString},// your json string goes here
With(
{
jsonStringFormatted: If(
Char(10) in jsonString,// json string is indented
jsonString,// then use the json string as is
Substitute(// else add newlines to allow for regular expression to match appropriately
Substitute(
Substitute(
jsonString,
"{",
"{" & Char(10)
),
"}",
"}" & Char(10)
),
",",
"," & Char(10)
)
)
},
ShowColumns(
AddColumns(
MatchAll(// use a regular expression formula with named subgroups to capture different types of json values and their keys
jsonStringFormatted,
"(?<arrayElement>(?:""(?<arrayKey>[a-zA-Z0-9_\s]*)"":\s*\[)\s*(?<arrayValue>[^-]*)])|(?<stringElement>(?:""(?<stringKey>[a-zA-Z0-9_\s]*)"":\s*[^\[])(?<stringValue>(?:.*))"")|(?<numberElement>(?:""(?<numberKey>[a-zA-Z0-9_\s]*)"":\s*[^\[])(?<numberValue>[0-9]*),)"
),
"Key",
Coalesce(// return the first non-blank key result from the named subgroups
arrayKey,
stringKey,
numberKey
),
"Value",
Coalesce(// return the first non-blank value result from the named subgroups
arrayValue,
stringValue,
numberValue
)
),
"Key",
"Value"
)
)
)
);
@ohthreesixtyfive
Copy link
Author

Updated to allow underscores (_) and spaces ( ) in keys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment