json-joy
Version:
Collection of libraries for building collaborative editing apps.
38 lines (37 loc) • 1.21 kB
JavaScript
import { escape as esc } from '@jsonjoy.com/util/lib/strings/escape';
import { sort } from '@jsonjoy.com/util/lib/sort/insertion';
const getKeys = Object.keys;
export const stringify = (val) => {
let i, max, str, keys, key, propVal;
switch (typeof val) {
case 'string':
return ('"' + esc(val) + '"');
case 'object':
if (val instanceof Array) {
str = '[';
max = val.length - 1;
for (i = 0; i < max; i++)
str += stringify(val[i]) + ',';
if (max >= 0)
str += stringify(val[i]);
return (str + ']');
}
if (val === null)
return 'null';
keys = sort(getKeys(val));
max = keys.length;
str = '{';
i = 0;
while (i < max) {
key = keys[i];
propVal = stringify(val[key]);
if (i && str !== '')
str += ',';
str += '"' + esc(key) + '":' + propVal;
i++;
}
return (str + '}');
default:
return String(val);
}
};