mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-25 23:24:09 +03:00
feat(JS to Object): handle backquotes
This commit is contained in:
1 parent
e073f3b99a
commit
4751417bf6
2 files changed
+12
-3
No files matched your search
@@ -6,7 +6,7 @@ export const tool = defineTool({
|
|||||||
name: translate('tools.javascript-to-json.title'),
|
name: translate('tools.javascript-to-json.title'),
|
||||||
path: '/javascript-to-json',
|
path: '/javascript-to-json',
|
||||||
description: translate('tools.javascript-to-json.description'),
|
description: translate('tools.javascript-to-json.description'),
|
||||||
keywords: ['javascript', 'to', 'json'],
|
keywords: ['javascript', 'json'],
|
||||||
component: () => import('./javascript-to-json.vue'),
|
component: () => import('./javascript-to-json.vue'),
|
||||||
icon: Braces,
|
icon: Braces,
|
||||||
createdAt: new Date('2024-03-29'),
|
createdAt: new Date('2024-03-29'),
|
||||||
|
|||||||
@@ -4,12 +4,21 @@ import type { UseValidationRule } from '@/composable/validation';
|
|||||||
import { isNotThrowing } from '@/utils/boolean';
|
import { isNotThrowing } from '@/utils/boolean';
|
||||||
import { withDefaultOnError } from '@/utils/defaults';
|
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 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>[] = [
|
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.',
|
message: 'Provided JS Object is not valid.',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
Reference in new issue
Block a user