Cookbook Ingredients - Code Snippets: Difference between revisions
Jump to navigation
Jump to search
(Posted on behalf of Reverend on Discord: https://discord.com/channels/296230822262865920/296659024818995200/872304827743481907) |
m (Taustin moved page cookbook Ingredients - Code Snippets to Cookbook Ingredients - Code Snippets without leaving a redirect) |
(3 intermediate revisions by 3 users not shown) | |
(No difference)
|
Latest revision as of 23:59, 25 April 2023
JSON
Find Name of Key Containing an Array Containing a Key/Value Pair
Given a JSON object like this one that contains arrays of states returned from getInfo("campaign"):
{ "other stuff":{}, "states":{ "no group": [ {"name":"Dead"... }, {"name":"Hidden"... } ] "my named group": [ {"name":"Blind"... }, {"name":"Deaf"... } ] }, "more stuff":{} }
To find the name of the key containing the array that has the desired key/value pair, e.g. for the state "Blind" return "my named group".
[h: jsonObject = getInfo("campaign")] [h: findKey = "name"] [h: findValue = "Blind"] [h: findWithin = "states"] [r: keyName = listGet(json.get(json.path.read(json.get(jsonObject, findWithin), strformat("\$..[?(@.%{findKey} == '%s')]", findValue), "AS_PATH_LIST"), 0), 1, "'")] alternatives [r: keyName = getGroup(strfind(jsonObject, '(?<=\\"'+findWithin+'\\":).*\\"([^\\"]+)\\"(?=:\\[)(?=.*\\"name\\":\\"'+findValue+'\\")'), 1, 1)] [r: keyName = replace(jsonObject, '.*(?<=\\"'+findWithin+'\\":).*\\"([^\\"]+)\\"(?=:\\[)(?=.*\\"'+findKey+'\\":\\"'+findValue+'\\").*',"\$1", 1)] [r: keyName = replace(json.get(jsonObject, findWithin),'.*?([^\\"]*)\\"\\:\\[[^\\[]*\\"'+findValue+'\\".*',"\$1", 1)]
Find Name of Key Containing an Object Containing a Key/Value Pair
Given a JSON object like this one that contains JSON objects
[h: jsonObj = '{ "a": { "Return": "No" }, "b": { "Return": "Yes" }, "c": { "Return": "No" } }']
To find the key name of the first object containing an occurance of "Return": "Yes"
[r: listGet(json.get(json.path.read(jsonObj, ".[?(@.Return == 'Yes')]", "AS_PATH_LIST"), 0), 1, "'")]
To get an array of all key names of objects containing an occurance of "Return": "Yes"
[r: replace(json.path.read(jsonObj, ".[?(@.Return == 'Yes')]", "AS_PATH_LIST"), "\\\$\\[\\'|\\'\\]", "")]