MyChat Scripts: function JSONKeyExists, checking if the key exists in JSON object
"For developers", "Server scripts", "Functions description", "JSON", "JSONKeyExists".
Check if the key exists with a specified name in JSON object. The letter case of the key does matter.
Syntax
function JSONKeyExist(const sJSON, sKey: string): boolean;
Parameters and return values
Parameter |
Type |
Value |
sJSON |
string |
JSON object as a text string; |
sKey |
string |
key name for checking. |
Function result
"True" if the key is inside of JSON object, "False" is there is no key with such name, JSON object is empty or incorrect.
Example
const
JSONOBJ = '{"age": 28, "sex": "male", "salary" : 1200}';
KEYS = 'age,sex,salary,birthday';
var
sData, sKey: string;
begin
sData := KEYS;
while length(sData) > 0 do begin
sKey := Fetch(sData, ',');
if JSONKeyExists(JSONOBJ, sKey) then mLogScript('Key "' + sKey + '" detected', '')
else mLogScript('Key "' + sKey + '" not detected', '')
end;
end.
Script work result
[19:59:42] (Log "JSONKeyExists"): Key "age" detected
[19:59:42] (Log "JSONKeyExists"): Key "sex" detected
[19:59:42] (Log "JSONKeyExists"): Key "salary" detected
[19:59:42] (Log "JSONKeyExists"): Key "birthday" not detected
[19:59:42] (Run "JSONKeyExists"): Script operation time: 8 ms
[19:59:42] (Run "JSONKeyExists"): Script done successfully.