siesta-lite
Version:
Stress-free JavaScript unit testing and functional testing tool, works in NodeJS and browsers
39 lines (35 loc) • 1.75 kB
text/typescript
function extractLineFeeds(s) {
return s.replace(/[^\n]+/g, '');
}
// input is the HanSON string to convert.
// if keepLineNumbers is set, toJSON() tried not to modify line numbers, so a JSON parser's
// line numbers in error messages will still make sense.
function toJSON(input, keepLineNumbers) {
var UNESCAPE_MAP = { '\\"': '"', "\\`": "`", "\\'": "'" };
var ML_ESCAPE_MAP = {'\n': '\\n', "\r": '\\r', "\t": '\\t', '"': '\\"'};
function unescapeQuotes(r) { return UNESCAPE_MAP[r] || r; }
return input.replace(/`(?:\\.|[^`])*`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|\/\*[^]*?\*\/|\/\/.*\n?/g, // pass 1: remove comments
function(s) {
if (s.charAt(0) == '/')
return keepLineNumbers ? extractLineFeeds(s) : '';
else
return s;
})
.replace(/(?:true|false|null)(?=[^\w_$]|$)|([a-zA-Z_$][\w_\-$]*)|`((?:\\.|[^`])*)`|'((?:\\.|[^'])*)'|"(?:\\.|[^"])*"|(,)(?=\s*[}\]])/g, // pass 2: requote
function(s, identifier, multilineQuote, singleQuote, lonelyComma) {
if (lonelyComma)
return '';
else if (identifier != null)
return '"' + identifier + '"';
else if (multilineQuote != null)
return '"' + multilineQuote.replace(/\\./g, unescapeQuotes).replace(/[\n\r\t"]/g, function(r) { return ML_ESCAPE_MAP[r]; }) +
'"' + (keepLineNumbers ? extractLineFeeds(multilineQuote) : '');
else if (singleQuote != null)
return '"' + singleQuote.replace(/\\./g, unescapeQuotes).replace(/"/g, '\\"') + '"';
else
return s;
});
}
export const parseRelaxedJson = (str : string) : object => {
return JSON.parse(toJSON(str, false))
}