Cookbook Ingredients - Code Snippets: Difference between revisions

From RPTools Wiki
Jump to navigation Jump to search
(Posted on behalf of Reverend on Discord: https://discord.com/channels/296230822262865920/296659024818995200/872304827743481907)
 
m (Melek moved page Cookbook Ingredients Setion (Code Snippets) to Cookbook Ingredients - Code Snippets without leaving a redirect: Remove parentheses from title and mispelling.)
(No difference)

Revision as of 04:30, 5 August 2021

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"), "\\\$\\[\\'|\\'\\]", "")]