Replaced parsing of JavaScript objects into JSON from `eval` to a dedicated `parseJS` function

This commit is contained in:
jos 2014-08-01 08:49:06 +02:00
parent 7ab134b95e
commit fb16ec4586
2 changed files with 59 additions and 1 deletions

View File

@ -3,6 +3,12 @@
https://github.com/josdejong/jsoneditor
## 2014-08-01, version 3.1.1
- Replaced parsing of JavaScript objects into JSON from `eval` to a dedicated
`parseJS` function.
## 2014-07-28, version 3.1.0
- JSONEditor now accepts JavaScript objects as input, and can turn them into

View File

@ -7,6 +7,7 @@ define(function () {
* Parse JSON using the parser built-in in the browser.
* On exception, the jsonString is validated and a detailed error is thrown.
* @param {String} jsonString
* @return {JSON} json
*/
util.parse = function parse(jsonString) {
try {
@ -15,7 +16,7 @@ define(function () {
catch (err) {
// try to load as JavaScript instead of JSON (like "{a: 2}" instead of "{"a": 2}"
try {
return eval('(' + jsonString + ')');
return util.parseJS(jsonString);
}
catch(err2) {
// ok no luck loading as JavaScript
@ -29,6 +30,57 @@ define(function () {
}
};
/**
* Parse a string containing an object in JavaScript notation into a JSON.
* Throws an error when not successful. This function can for example parse
* a string like "{a: 2, 'b': {c: 'd'}".
* @param {string} jsString
* @returns {JSON} json
*/
util.parseJS = function (jsString) {
// escape quotes inside strings
var chars = [];
var inString = false;
var i = 0;
while(i < jsString.length) {
var c = jsString.charAt(i);
if (c === '"' || c === '\'') {
if (c === inString) {
// end of string
inString = false;
}
else if (!inString) {
// start of string
inString = c;
}
else {
// add escape character if not escaped
if (jsString.charAt(i - 1) !== '\\') {
chars.push('\\');
}
}
}
chars.push(c);
i++;
}
var jsonString = chars.join('');
// replace keys/values enclosed by single quotes with double quotes
jsonString = jsonString.replace(/(.)'/g, function ($0, $1) {
var str = $1.replace(/"/g, '\\"'); // escape double quotes
return ($1 == '\\') ? '\'' : str + '"';
});
// enclose unquoted object keys with double quotes
jsonString = jsonString.replace(/([{,]\s*)([a-zA-Z_][a-zA-Z0-9_]*)(\s*:)/g, function ($0, $1, $2, $3) {
return $1 + '"' + $2 + '"' + $3;
});
return JSON.parse(jsonString);
};
/**
* Validate a string containing a JSON object
* This method uses JSONLint to validate the String. If JSONLint is not