mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-05-09 15:45:01 -04:00
feat(json-prettify): sort keys
This commit is contained in:
parent
863c8d0f6a
commit
f3aa475cb5
3 changed files with 69 additions and 3 deletions
35
src/tools/json-viewer/json.models.ts
Normal file
35
src/tools/json-viewer/json.models.ts
Normal file
|
@ -0,0 +1,35 @@
|
|||
import { get, type MaybeRef } from '@vueuse/core';
|
||||
import JSON5 from 'json5';
|
||||
|
||||
export { sortObjectKeys, formatJson };
|
||||
|
||||
function sortObjectKeys<T>(obj: T): T {
|
||||
if (typeof obj !== 'object' || obj === null) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map(sortObjectKeys) as T;
|
||||
}
|
||||
|
||||
return Object.keys(obj)
|
||||
.sort()
|
||||
.reduce((sortedObj, key) => {
|
||||
sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);
|
||||
return sortedObj;
|
||||
}, {} as Record<string, unknown>) as T;
|
||||
}
|
||||
|
||||
function formatJson({
|
||||
rawJson,
|
||||
sortKeys = true,
|
||||
indentSize = 3,
|
||||
}: {
|
||||
rawJson: MaybeRef<string>;
|
||||
sortKeys?: MaybeRef<boolean>;
|
||||
indentSize?: MaybeRef<number>;
|
||||
}) {
|
||||
const parsedObject = JSON5.parse(get(rawJson));
|
||||
|
||||
return JSON.stringify(get(sortKeys) ? sortObjectKeys(parsedObject) : parsedObject, null, get(indentSize));
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue