Search code examples
javascriptparsingevalstringify

How to De-Stringify Stringified JavaScript?


How to 'de-stringify' JavaScript code that has been stringified? JSON.parse does not seem to work. We want to store JavaScript code in the database and then retrieve it and then eval it. Here's the code in the database:

//# sourceURL=journal.js

function onBlur(e) {

    var drAmount = script.getGridRowFieldValue('debitamount', e.rowuid)
    var crAmount = script.getGridRowFieldValue('creditamount', e.rowuid);

    // Prevent both debit and credit from having values.      
    if (drAmount != undefined && crAmount != undefined) {

        if (e.fieldname == 'debitamount') {
            script.setGridRowFieldValue('creditamount', e, undefined)
        } else if (e.fieldname == 'creditamount') {
            script.setGridRowFieldValue('debitamount', e, undefined)
        }

    }
}

Here's what's returned:

"//# sourceURL=journal.js\r\n\r\nexport function onBlur(e) {\r\n\r\n var drAmount = script.getGridRowFieldValue('debitamount', e.rowuid)\r\n var crAmount = script.getGridRowFieldValue('creditamount', e.rowuid);\r\n\r\n // Prevent both debit and credit from having values. \r\n if (drAmount != undefined && crAmount != undefined) {\r\n\r\n if (e.fieldname == 'debitamount') {\r\n script.setGridRowFieldValue('creditamount', e, undefined)\r\n } else if (e.fieldname == 'creditamount') {\r\n script.setGridRowFieldValue('debitamount', e, undefined)\r\n }\r\n\r\n }\r\n}\r\n\r\n\r\n\r\n\r\n"


Solution

  • You should try to extract your object's behaviour from it's data. It's generally a bad thing to use eval, specially if you can't trust the string you are parsing. You should store the data as json, and the functions that consume the data should be static and be added to your object via prototype or something like that.