MDL-76508 templates: Handling non-JSON string

When the param string contains a left curly bracket as the first character,
the system will assume the string is a JSON string and will be parsed and returned as an object.
But in some cases, the string is not JSON and will return an error if the system parses it.
For example, a user might have used the course name with a left curly bracket as the first character.
Adding a double quote after the left curly bracket to differentiate between string and JSON string,
so it can be safe to parse the string, and also added try..catch to ensure that the parsing creates an object type.
This commit is contained in:
Meirza 2022-12-06 15:28:24 +07:00
parent 15a695d573
commit fbc2732d9f
3 changed files with 17 additions and 4 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -556,9 +556,22 @@ function(
// Allow variable expansion in the param part only.
param = helper(param, context);
}
// Allow json formatted $a arguments.
if ((param.indexOf('{') === 0) && (param.indexOf('{{') !== 0)) {
param = JSON.parse(param);
// Added double quote after left curly bracket to differentiate between string and JSON string.
if (param.indexOf('{"') === 0) {
// If it can't be parsed then the string is not a JSON format.
try {
const parsedParam = JSON.parse(param);
// Handle non-exception-throwing cases, e.g. null, integer, boolean.
if (parsedParam && typeof parsedParam === "object") {
param = parsedParam;
}
} catch (err) {
// This was probably not JSON.
// Keep the error message visible.
window.console.warn(err.message);
}
}
var index = this.requiredStrings.length;