feat(JS to Object): handle backquotes

This commit is contained in:
ShareVB committed 2025-05-08 13:30:50 +02:00
1 parent e073f3b99a
commit 4751417bf6
2 files changed
+12 -3

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ export const tool = defineTool({
name: translate('tools.javascript-to-json.title'),
path: '/javascript-to-json',
description: translate('tools.javascript-to-json.description'),
keywords: ['javascript', 'to', 'json'],
keywords: ['javascript', 'json'],
component: () => import('./javascript-to-json.vue'),
icon: Braces,
createdAt: new Date('2024-03-29'),
@@ -4,12 +4,21 @@ import type { UseValidationRule } from '@/composable/validation';
import { isNotThrowing } from '@/utils/boolean';
import { withDefaultOnError } from '@/utils/defaults';
function parseJSON(value: string) {
try {
return JSON5.parse(value);
}
catch {
return JSON5.parse(value.replace(/`((?:[^`]|\\`)*)`/g, (_m, s) => `"${s.replace(/"/g, '\\""').replace(/\r/g, '\\r').replace(/\n/g, '\\n')}"`));
}
}
const indentSize = useStorage('json-prettify:indent-size', 3);
const transformer = (value: string) => withDefaultOnError(() => JSON.stringify(JSON5.parse(value), null, indentSize.value), '');
const transformer = (value: string) => withDefaultOnError(() => JSON.stringify(parseJSON(value), null, indentSize.value), '');
const rules: UseValidationRule<string>[] = [
{
validator: (value: string) => value === '' || isNotThrowing(() => JSON.stringify(JSON5.parse(value))),
validator: (value: string) => value === '' || isNotThrowing(() => JSON.stringify(parseJSON(value))),
message: 'Provided JS Object is not valid.',
},
];