mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-20 21:23:08 +03:00
feat(JSON Viewer): add unescape JSON string
Fix JSON.parseBigNum edge cases Inspired by #1673 from @iyuq
This commit is contained in:
1 parent
95590f1d7b
commit
c4c6d3883f
6 files changed
+150
-10
No files matched your search
@@ -5798,6 +5798,7 @@ tools:
|
||||
label-json-schema: 'JSON schema:'
|
||||
placeholder-paste-your-json-schema-here: Paste your JSON Schema here...
|
||||
title-schema-validation-errors: Schema Validation Errors
|
||||
label-unescape-json-string: 'Unescape JSON string:'
|
||||
text:
|
||||
provided-json-is-not-valid: Provided JSON is not valid.
|
||||
try-again-with-repairjsonlabel: Try again with "{0}"
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { jsonrepair } from 'jsonrepair';
|
||||
import {
|
||||
get,
|
||||
} from '@vueuse/core';
|
||||
@@ -21,20 +20,21 @@ const schemaData = useITStorage('json-prettify:schema-data', '');
|
||||
const indentSize = useITStorage('json-prettify:indent-size', 3);
|
||||
const sortKeys = useITStorage('json-prettify:sort-keys', true);
|
||||
const unescapeUnicode = useITStorage('json-prettify:unescape-unicode', false);
|
||||
const unescapeJsonString = useITStorage('json-prettify:unescape-json', false);
|
||||
const repairJson = useITStorage('json-prettify:repair-json', true);
|
||||
const cleanJson = computed(() => withDefaultOnError(() => formatJson({ rawJson, indentSize, sortKeys, unescapeUnicode, repairJson }), ''));
|
||||
const cleanJson = computed(() => withDefaultOnError(() => formatJson({ rawJson, indentSize, sortKeys, unescapeUnicode, unescapeJsonString, repairJson }), ''));
|
||||
|
||||
const rawJsonValidation = useValidation({
|
||||
source: rawJson,
|
||||
rules: [
|
||||
{
|
||||
validator: v => v === '' || (get(repairJson) ? jsonrepair(v) : JSON.parseBigNum(v)),
|
||||
validator: v => v === '' || formatJson({ rawJson, indentSize: 0, sortKeys: false, unescapeUnicode, unescapeJsonString, repairJson }),
|
||||
get message() {
|
||||
return t('tools.json-viewer.text.provided-json-is-not-valid') + (!get(repairJson) ? t('tools.json-viewer.text.try-again-with-repairjsonlabel', [repairJsonLabel]) : '');
|
||||
},
|
||||
},
|
||||
],
|
||||
watch: [repairJson],
|
||||
watch: [repairJson, unescapeUnicode, unescapeJsonString],
|
||||
});
|
||||
|
||||
const schemaUrl = useQueryParamOrStorage<string>({ name: 'schema', storageName: 'json-prettify:schema', defaultValue: '' });
|
||||
@@ -49,6 +49,9 @@ const { schemas, errors: validationErrors } = useJsonSchemaValidation({ json: ra
|
||||
<n-form-item :label="t('tools.json-viewer.texts.label-unescape-unicode')" label-placement="left" label-width="150">
|
||||
<n-switch v-model:value="unescapeUnicode" />
|
||||
</n-form-item>
|
||||
<n-form-item :label="t('tools.json-viewer.texts.label-unescape-json-string')" label-placement="left" label-width="180">
|
||||
<n-switch v-model:value="unescapeJsonString" />
|
||||
</n-form-item>
|
||||
<n-form-item :label="t('tools.json-viewer.texts.label-indent-size')" label-placement="left" label-width="100" :show-feedback="false">
|
||||
<n-input-number-i18n v-model:value="indentSize" min="0" max="10" style="width: 100px" />
|
||||
</n-form-item>
|
||||
|
||||
@@ -27,5 +27,104 @@ describe('json models', () => {
|
||||
expect(() => formatJson({ rawJson, sortKeys: false, repairJson: false })).to.throw();
|
||||
});
|
||||
});
|
||||
|
||||
const testJson = '{"b": 2, "a": 1}';
|
||||
const expectedSorted = '{\n "a": 1,\n "b": 2\n}';
|
||||
const expectedUnsorted = '{\n "b": 2,\n "a": 1\n}';
|
||||
|
||||
it('formats JSON with default options (sorted keys, 3 spaces)', () => {
|
||||
const result = formatJson({ rawJson: testJson });
|
||||
expect(result).toBe(expectedSorted);
|
||||
});
|
||||
|
||||
it('formats JSON without sorting keys when sortKeys is false', () => {
|
||||
const result = formatJson({ rawJson: testJson, sortKeys: false });
|
||||
expect(result).toBe(expectedUnsorted);
|
||||
});
|
||||
|
||||
it('formats JSON with custom indent size', () => {
|
||||
const result = formatJson({ rawJson: testJson, indentSize: 2 });
|
||||
const expected = '{\n "a": 1,\n "b": 2\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('works with reactive refs', () => {
|
||||
const rawJsonRef = ref(testJson);
|
||||
const sortKeysRef = ref(true);
|
||||
const indentSizeRef = ref(3);
|
||||
|
||||
const result = formatJson({
|
||||
rawJson: rawJsonRef,
|
||||
sortKeys: sortKeysRef,
|
||||
indentSize: indentSizeRef,
|
||||
});
|
||||
expect(result).toBe(expectedSorted);
|
||||
});
|
||||
|
||||
describe('autoUnescape functionality', () => {
|
||||
it('unescapes escaped JSON strings when autoUnescape is true', () => {
|
||||
const escapedJson = '"{\\\"id\\\":\\\"123\\\",\\\"name\\\":\\\"test\\\"}"';
|
||||
const result = formatJson({ rawJson: escapedJson, unescapeJsonString: true, indentSize: 2 });
|
||||
const expected = '{\n "id": "123",\n "name": "test"\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('handles escaped JSON without outer quotes', () => {
|
||||
const escapedJson = '{\\\"id\\\":\\\"123\\\",\\\"name\\\":\\\"test\\\"}';
|
||||
const result = formatJson({ rawJson: escapedJson, unescapeJsonString: true, indentSize: 2 });
|
||||
const expected = '{\n "id": "123",\n "name": "test"\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('unescapes various escape sequences', () => {
|
||||
const escapedJson = '{\\\"text\\\":\\\"Hello\\\\\\\\World\\\",\\\"path\\\":\\\"/api\\\\/test\\\"}';
|
||||
const result = formatJson({ rawJson: escapedJson, unescapeJsonString: true, indentSize: 2 });
|
||||
const expected = '{\n "path": "/api/test",\n "text": "Hello\\\\World"\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('handles single-quoted outer strings', () => {
|
||||
const escapedJson = '\'{\\\"id\\\":\\\"123\\\"}\'';
|
||||
const result = formatJson({ rawJson: escapedJson, unescapeJsonString: true, indentSize: 2 });
|
||||
const expected = '{\n "id": "123"\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('processes regular JSON normally when autoUnescape is false', () => {
|
||||
const normalJson = '{"id":"123","name":"test"}';
|
||||
const result = formatJson({ rawJson: normalJson, unescapeJsonString: false, indentSize: 2 });
|
||||
const expected = '{\n "id": "123",\n "name": "test"\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('handles malformed escaped JSON gracefully', () => {
|
||||
const malformedJson = '"{\\\"incomplete';
|
||||
// Should fall back to original string and fail parsing
|
||||
expect(() => formatJson({ rawJson: malformedJson, unescapeJsonString: true })).toThrow();
|
||||
});
|
||||
|
||||
it('works with complex nested objects', () => {
|
||||
const complexEscaped = '"{\\\"users\\\":[{\\\"id\\\":\\\"1\\\",\\\"data\\\":{\\\"active\\\":true}}],\\\"meta\\\":{\\\"total\\\":1}}"';
|
||||
const result = formatJson({ rawJson: complexEscaped, unescapeJsonString: true, indentSize: 2 });
|
||||
const expected = '{\n "meta": {\n "total": 1\n },\n "users": [\n {\n "data": {\n "active": true\n },\n "id": "1"\n }\n ]\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it('works with reactive autoUnescape ref', () => {
|
||||
const escapedJson = '"{\\\"test\\\":\\\"value\\\"}"';
|
||||
const autoUnescapeRef = ref(true);
|
||||
const result = formatJson({ rawJson: escapedJson, unescapeJsonString: autoUnescapeRef, indentSize: 2 });
|
||||
const expected = '{\n "test": "value"\n}';
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
it('handles empty string input', () => {
|
||||
expect(() => formatJson({ rawJson: '' })).toThrow();
|
||||
});
|
||||
|
||||
it('handles invalid JSON input', () => {
|
||||
expect(() => formatJson({ rawJson: 'invalid json' })).toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -27,20 +27,56 @@ function unescapeUnicodeJSON(str: string) {
|
||||
);
|
||||
}
|
||||
|
||||
function unescapeJson(jsonString: string): string {
|
||||
try {
|
||||
// First, try to handle double-escaped scenarios
|
||||
let result = jsonString.trim();
|
||||
|
||||
// If the string starts and ends with quotes, and contains escaped quotes inside,
|
||||
// it might be a JSON string that needs to be unescaped
|
||||
if ((result.startsWith('"') && result.endsWith('"'))
|
||||
|| (result.startsWith('\'') && result.endsWith('\''))) {
|
||||
// Remove outer quotes first
|
||||
result = result.slice(1, -1);
|
||||
}
|
||||
|
||||
// Handle common escape sequences
|
||||
result = result
|
||||
.replace(/\\"/g, '"') // Unescape quotes
|
||||
.replace(/\\\\/g, '\\') // Unescape backslashes (do this after quotes!)
|
||||
.replace(/\\n/g, '\n') // Unescape newlines
|
||||
.replace(/\\r/g, '\r') // Unescape carriage returns
|
||||
.replace(/\\t/g, '\t') // Unescape tabs
|
||||
.replace(/\\f/g, '\f') // Unescape form feeds
|
||||
.replace(/\\b/g, '\b') // Unescape backspaces
|
||||
.replace(/\\\//g, '/'); // Unescape forward slashes
|
||||
|
||||
return result;
|
||||
}
|
||||
catch {
|
||||
return jsonString;
|
||||
}
|
||||
}
|
||||
|
||||
function formatJson({
|
||||
rawJson,
|
||||
sortKeys = true,
|
||||
indentSize = 3,
|
||||
unescapeUnicode = false,
|
||||
unescapeJsonString = false,
|
||||
repairJson = false,
|
||||
}: {
|
||||
rawJson: MaybeRef<string>
|
||||
sortKeys?: MaybeRef<boolean>
|
||||
indentSize?: MaybeRef<number>
|
||||
unescapeUnicode?: MaybeRef<boolean>
|
||||
unescapeJsonString?: MaybeRef<boolean>
|
||||
repairJson?: MaybeRef<boolean>
|
||||
}) {
|
||||
const unwrappedJson = get(rawJson);
|
||||
let unwrappedJson = get(rawJson)?.trim();
|
||||
if (get(unescapeJsonString)) {
|
||||
unwrappedJson = unescapeJson(unwrappedJson);
|
||||
}
|
||||
const jsonString = get(repairJson) ? jsonrepair(unwrappedJson) : unwrappedJson;
|
||||
const parsedObject = JSON.parseBigNum(get(unescapeUnicode) ? unescapeUnicodeJSON(jsonString) : jsonString);
|
||||
|
||||
|
||||
@@ -30,14 +30,15 @@ JSON.parseBigInt = function (jsonStr: string, options?: { minDigits?: number }):
|
||||
return JSON5.parse(safeStr, (_key, value) => {
|
||||
if (typeof value === 'string') {
|
||||
if (bigintRegex.test(value)) {
|
||||
const bigintValue = value.slice(1, -1);
|
||||
try {
|
||||
if (typeof BigInt !== 'undefined') {
|
||||
// take only part xxx between ¤xxx¤
|
||||
return BigInt(value.substring(1, value.length - 1));
|
||||
return BigInt(bigintValue);
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return value;
|
||||
return bigintValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,9 +29,9 @@ JSON.parseBigNum = function (jsonStr: string): unknown {
|
||||
return JSON5.parse(safeStr, (_key, value) => {
|
||||
if (typeof value === 'string') {
|
||||
if (bignumRegex.test(value)) {
|
||||
// take only part xxx between ¤xxx¤
|
||||
const number_string = value.slice(1, -1);
|
||||
try {
|
||||
// take only part xxx between ¤xxx¤
|
||||
const number_string = value.substring(1, value.length - 1);
|
||||
const full_precision = new Decimal(number_string);
|
||||
const json_number = Number(number_string);
|
||||
if (json_number.toString() === full_precision.toString()) {
|
||||
@@ -42,7 +42,7 @@ JSON.parseBigNum = function (jsonStr: string): unknown {
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return value;
|
||||
return number_string;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user