Cookbook Ingredients - Code Snippets

From RPTools Wiki
Jump to navigationJump to search

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