feat(JSON Prettifier): add unescape unicode

This commit is contained in:
ShareVB committed 2025-04-21 22:18:41 +02:00
commit b824880b21
2 files changed
+15 -2

No files matched your search

+5 -1
View File
@@ -11,7 +11,8 @@ const inputElement = ref<HTMLElement>();
const rawJson = useStorage('json-prettify:raw-json', '{"hello": "world", "foo": "bar"}');
const indentSize = useStorage('json-prettify:indent-size', 3);
const sortKeys = useStorage('json-prettify:sort-keys', true);
const cleanJson = computed(() => withDefaultOnError(() => formatJson({ rawJson, indentSize, sortKeys }), ''));
const unescapeUnicode = useStorage('json-prettify:unescape-unicode', false);
const cleanJson = computed(() => withDefaultOnError(() => formatJson({ rawJson, indentSize, sortKeys, unescapeUnicode }), ''));
const rawJsonValidation = useValidation({
source: rawJson,
@@ -30,6 +31,9 @@ const rawJsonValidation = useValidation({
<n-form-item label="Sort keys :" label-placement="left" label-width="100">
<n-switch v-model:value="sortKeys" />
</n-form-item>
<n-form-item label="Unescape Unicode :" label-placement="left" label-width="150">
<n-switch v-model:value="unescapeUnicode" />
</n-form-item>
<n-form-item label="Indent size :" label-placement="left" label-width="100" :show-feedback="false">
<n-input-number v-model:value="indentSize" min="0" max="10" style="width: 100px" />
</n-form-item>
+10 -1
View File
@@ -20,16 +20,25 @@ function sortObjectKeys<T>(obj: T): T {
}, {} as Record<string, unknown>) as T;
}
function unescapeUnicodeJSON(str: string) {
return str.replace(/\\u([\dA-Fa-f]{4})/g, (match, grp) =>
String.fromCharCode(Number.parseInt(grp, 16)),
);
}
function formatJson({
rawJson,
sortKeys = true,
indentSize = 3,
unescapeUnicode = false,
}: {
rawJson: MaybeRef<string>
sortKeys?: MaybeRef<boolean>
indentSize?: MaybeRef<number>
unescapeUnicode?: MaybeRef<boolean>
}) {
const parsedObject = JSON5.parse(get(rawJson));
const raw = get(rawJson);
const parsedObject = JSON5.parse(get(unescapeUnicode) ? unescapeUnicodeJSON(raw) : raw);
return JSON.stringify(get(sortKeys) ? sortObjectKeys(parsedObject) : parsedObject, null, get(indentSize));
}