In the application I am working on, I have some configuration stored in a memo field in object literals.
{
JWT : { endpoint :"https://somelink1",
clientid :"consent-management",
grantType :"client_credentials" },
CMP : {endpoint :"https://someotherlink2",
contentType :"application/json"}
}
Using regex and application specific javascript language, I am maching the object part only and parsing it
var auth = nms.extAccount.load(39010);
var regex = /{([^;]*)}/gm;
var authObj = JSON.parse(JSON.stringify(auth.comment.match(regex)));
logInfo(authObj);
Normaly I would then just use dot notation authObj.JWT.endpoint)
to navigate through the object but it isnt working.
14/05/2024 13:25:47 js JST-310000 Error while compiling script 'WKF9/js' line 6: authObj.JWT is undefined.
Just wondering if I am missing something.
I log the type and is object
14/05/2024 14:24:32 js object
3
Answers
I believe the regex will match the first open curly brace (before JWT) up to the first closing brace (after "client_credentials").
Perhaps you can just remove the "DO NOT CHANGE" part of the comment and then parse it:
let authObj = JSON.parse(auth.comment.replace('***DO NOT CHANGE***', ''));
or if that won’t work for every case, then the regex likely needs to be corrected to parse out the full JSON text.
How about treating the config as string but sanitizing it towards a valid JSON-string by a simple
replace
task, where the following regex …/w+(?=s*:s*["{])/gm
… does match each of the config’s keys.And in order to remove the asterisk suffixed/prefixed comment(s) another regex based …
/s****.*?***s+/gm
…replace
task needs to be run before the parsing into an authorization object can be safely approached.Note
Whereas the first introduced key-matching regex is already sufficient enough, another regex like …
/(?<=[{,]s*)w+(?=s*:s*["{])/gm
… is even more reliable. This lately introduced regex makes not only use of a positive lookahead like the former one, but also uses a positive lookbehind which might not be supported by some older JS-engines.Just eval it in an arrow function if you trust the code: