Checking the validity of json before parsing and adding stringifyJSON JS Function

Signed-off-by: iifawzi <iifawzie@gmail.com>
This commit is contained in:
iifawzi 2023-01-14 17:12:33 +02:00
parent b60d1454ca
commit cb6012cf2a
2 changed files with 21 additions and 12 deletions

View File

@ -3980,6 +3980,21 @@ Functions.getCellValue = function (td) {
}
};
/**
* Validate and return stringified JSON inputs, or plain if invalid.
*
* @param json the json input to be validated and stringified
* @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
* @return {string}
*/
Functions.stringifyJSON = function (json, replacer = null, space = 0) {
try {
json = JSON.stringify(JSON.parse(json), replacer, space);
} catch (e) { }
return json;
};
/**
* Unbind all event handlers before tearing down a page
*/

View File

@ -631,11 +631,7 @@ var makeGrid = function (t, enableResize, enableReorder, enableVisib, enableGrid
// fill the cell edit with text from <td>
var value = Functions.getCellValue(cell);
if ($cell.attr('data-type') === 'json' && $cell.is('.truncated') === false) {
try {
value = JSON.stringify(JSON.parse(value), null, 4);
} catch (e) {
// Show as is
}
value = Functions.stringifyJSON(value, null, 4);
}
$(g.cEdit).find('.edit_box').val(value);
@ -1053,11 +1049,7 @@ var makeGrid = function (t, enableResize, enableReorder, enableVisib, enableGrid
$editArea.removeClass('edit_area_loading');
if (typeof data !== 'undefined' && data.success === true) {
if ($td.attr('data-type') === 'json') {
try {
data.value = JSON.stringify(JSON.parse(data.value), null, 4);
} catch (e) {
// Show as is
}
data.value = Functions.stringifyJSON(data.value, null, 4);
}
$td.data('original_data', data.value);
$(g.cEdit).find('.edit_box').val(data.value);
@ -1278,7 +1270,8 @@ var makeGrid = function (t, enableResize, enableReorder, enableVisib, enableGrid
if ($thisField.attr('data-type') !== 'json') {
fields.push($thisField.data('value'));
} else {
fields.push(JSON.stringify(JSON.parse($thisField.data('value'))));
const JSONString = Functions.stringifyJSON($thisField.data('value'));
fields.push(JSONString);
}
var cellIndex = $thisField.index('.to_be_saved');
@ -1520,7 +1513,8 @@ var makeGrid = function (t, enableResize, enableReorder, enableVisib, enableGrid
if ($thisField.attr('data-type') !== 'json') {
isValueUpdated = thisFieldParams[fieldName] !== Functions.getCellValue(g.currentEditCell);
} else {
isValueUpdated = JSON.stringify(JSON.parse(thisFieldParams[fieldName])) !== JSON.stringify(JSON.parse(Functions.getCellValue(g.currentEditCell)));
const JSONString = Functions.stringifyJSON(thisFieldParams[fieldName]);
isValueUpdated = JSONString !== JSON.stringify(JSON.parse(Functions.getCellValue(g.currentEditCell)));
}
if (g.wasEditedCellNull || isValueUpdated) {