@scalar/oas-utils
Version:
Open API spec and Yaml handling utilities
43 lines (40 loc) • 1.09 kB
JavaScript
import { isJsonString } from './parse.js';
/**
* Takes JSON and formats it.
*/
const prettyPrintJson = (value) => {
if (typeof value === 'string') {
// JSON string
if (isJsonString(value)) {
return JSON.stringify(JSON.parse(value), null, 2);
}
// Regular string
return value;
}
// Object
if (typeof value === 'object') {
try {
return JSON.stringify(value, null, 2);
}
catch {
return replaceCircularDependencies(value);
}
}
return value?.toString() ?? '';
};
/**
* JSON.stringify, but with circular dependencies replaced with '[Circular]'
*/
function replaceCircularDependencies(content) {
const cache = new Set();
return JSON.stringify(content, (_key, value) => {
if (typeof value === 'object' && value !== null) {
if (cache.has(value)) {
return '[Circular]';
}
cache.add(value);
}
return value;
}, 2);
}
export { prettyPrintJson, replaceCircularDependencies };