Skip to content

Commit

Permalink
Add JSON filter
Browse files Browse the repository at this point in the history
  • Loading branch information
igr committed Aug 18, 2022
1 parent 8b7b7de commit 8fd4076
Showing 1 changed file with 2 additions and 26 deletions.
28 changes: 2 additions & 26 deletions src/filters/out.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as SpigConfig from '../spig-config';
import { escape } from './json';

/**
* Returns the JSON representation of an object.
Expand All @@ -23,21 +24,6 @@ function toJSON(object: object, objectMaxDepth: number, arrayMaxLength: number,
const paths: string[] = [];
// A list of all the objects that were seen (used to avoid recursion)
const values: object[] = [];
// The replacement characters
const replacements: { [key: string]: string } = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\',
};

// Matches characters that must be escaped
// eslint-disable-next-line no-misleading-character-class,no-control-regex
const escapable =
/[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;

/**
* Escapes control characters, quote characters, backslash characters and quotes the string.
Expand All @@ -46,17 +32,7 @@ function toJSON(object: object, objectMaxDepth: number, arrayMaxLength: number,
* @returns {String} the quoted string
*/
function quote(string: string): string {
escapable.lastIndex = 0;
let escaped;
if (escapable.test(string)) {
escaped = string.replace(escapable, (a) => {
const replacement = replacements[a];
if (replacement) return replacement;
// Pad the unicode representation with leading zeros, up to 4 characters.
return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
} else escaped = string;
return '"' + escaped + '"';
return '"' + escape(string) + '"';
}

/**
Expand Down

0 comments on commit 8fd4076

Please sign in to comment.