From fbe531e2c9b1bfa275005e2bbcd50e860942bf93 Mon Sep 17 00:00:00 2001 From: nawfal Date: Thu, 4 Jun 2026 09:00:10 +0700 Subject: [PATCH 01/12] feat(json-to-csv): accept NDJSON / multiple objects without array wrapper The JSON to CSV tool only accepted a single JSON value, so pasting several objects (one per line) without wrapping them in an array failed with "Invalid JSON input." (#353). Add a reusable `parseJsonOrNdjson()` helper in `utils/json` that parses standard JSON first and falls back to NDJSON (newline-delimited JSON / JSON Lines): each non-empty line is parsed and the records are returned as an array. A single non-JSON line still surfaces as a normal JSON error, so genuinely invalid input is not misread as NDJSON. The helper lives in `utils/json` so other JSON tools can adopt the same behavior. Wire it into `convertJsonToCsv` and cover it with tests (multi-line objects, blank-line skipping, sparse keys, and the invalid-line case). Closes #353 Co-Authored-By: Claude Opus 4.8 --- .../tools/json/json-to-csv/service.test.ts | 34 ++++++++++++ src/pages/tools/json/json-to-csv/service.ts | 4 +- src/utils/json.ts | 53 +++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/src/pages/tools/json/json-to-csv/service.test.ts b/src/pages/tools/json/json-to-csv/service.test.ts index f6a2011c..8370a87d 100644 --- a/src/pages/tools/json/json-to-csv/service.test.ts +++ b/src/pages/tools/json/json-to-csv/service.test.ts @@ -169,4 +169,38 @@ describe('convertJsonToCsv', () => { ).toThrow('No data found in the provided JSON.'); }); }); + + describe('NDJSON (newline-delimited JSON)', () => { + it('converts objects on separate lines without an array wrapper', () => { + const input = [ + '{"key1": "AAA", "key2": "XXX"}', + '{"key1": "BBB", "key2": "YYY"}', + '{"key1": "CCC", "key2": "ZZZ"}' + ].join('\n'); + + expect(convertJsonToCsv(input, defaultOptions)).toBe( + `key1,key2\r\nAAA,XXX\r\nBBB,YYY\r\nCCC,ZZZ` + ); + }); + + it('ignores blank lines between NDJSON records', () => { + const input = '{"a": 1}\n\n{"a": 2}\n'; + + expect(convertJsonToCsv(input, defaultOptions)).toBe(`a\r\n1\r\n2`); + }); + + it('handles sparse keys across NDJSON records', () => { + const input = '{"a": 1}\n{"b": 2}'; + + expect(convertJsonToCsv(input, defaultOptions)).toBe(`a,b\r\n1,\r\n,2`); + }); + + it('still throws when one NDJSON line is not valid JSON', () => { + const input = '{"a": 1}\nnot json'; + + expect(() => convertJsonToCsv(input, defaultOptions)).toThrow( + 'Invalid JSON input.' + ); + }); + }); }); diff --git a/src/pages/tools/json/json-to-csv/service.ts b/src/pages/tools/json/json-to-csv/service.ts index 33ddeb4e..529773e0 100644 --- a/src/pages/tools/json/json-to-csv/service.ts +++ b/src/pages/tools/json/json-to-csv/service.ts @@ -1,5 +1,5 @@ import { InitialValuesType } from './types'; -import { getJsonHeaders } from 'utils/json'; +import { getJsonHeaders, parseJsonOrNdjson } from 'utils/json'; /** * Recursively flattens any JSON value into a flat object. @@ -87,7 +87,7 @@ export function convertJsonToCsv( let parsed: unknown; try { - parsed = JSON.parse(input); + parsed = parseJsonOrNdjson(input); } catch { throw new Error('Invalid JSON input.'); } diff --git a/src/utils/json.ts b/src/utils/json.ts index c243ab37..ad21d277 100644 --- a/src/utils/json.ts +++ b/src/utils/json.ts @@ -1,3 +1,56 @@ +/** + * Parses a JSON string, falling back to NDJSON (newline-delimited JSON, a.k.a. + * JSON Lines) when the input is not a single valid JSON value. + * + * This lets users paste multiple JSON objects without wrapping them in an + * array, e.g.: + * + * {"key1": "AAA"} + * {"key1": "BBB"} + * + * Standard JSON (an object or array) is parsed first and returned unchanged. + * Otherwise each non-empty line must be a valid JSON value, and the values are + * returned as an array. A single line that is not valid JSON is reported as a + * plain JSON error rather than being misread as NDJSON. + * + * @param input - Raw text to parse + * @returns The parsed JSON value, or an array of values when NDJSON is detected + * @throws SyntaxError when the input is neither valid JSON nor valid NDJSON + * + * @example + * parseJsonOrNdjson('{"a":1}\n{"a":2}') // → [{ a: 1 }, { a: 2 }] + */ +export function parseJsonOrNdjson(input: string): unknown { + const trimmed = input.trim(); + + try { + return JSON.parse(trimmed); + } catch (jsonError) { + const lines = trimmed + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); + + // A single line that already failed JSON.parse is not NDJSON — surface the + // original error instead of masking it. + if (lines.length < 2) { + throw jsonError; + } + + const values: unknown[] = []; + for (const line of lines) { + try { + values.push(JSON.parse(line)); + } catch { + // Not valid NDJSON either — report the original JSON parse failure. + throw jsonError; + } + } + + return values; + } +} + /** * Collects all unique keys from an array of row objects, preserving first-encountered order. * Handles sparse rows where different rows may have different keys. From 2254b559a7f1dfa79e7941ecfeab4d5a304dd3b3 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 01:46:26 +0200 Subject: [PATCH 02/12] chore: improved jsonparser util function --- src/utils/json.ts | 101 +++++++++++++++++++++++++++------------------- 1 file changed, 59 insertions(+), 42 deletions(-) diff --git a/src/utils/json.ts b/src/utils/json.ts index ad21d277..f9722cea 100644 --- a/src/utils/json.ts +++ b/src/utils/json.ts @@ -1,56 +1,66 @@ +export type ParsedJson = + | Record + | unknown[] + | string + | number + | boolean + | null; + /** - * Parses a JSON string, falling back to NDJSON (newline-delimited JSON, a.k.a. - * JSON Lines) when the input is not a single valid JSON value. + * Parses a JSON string into its JavaScript representation. * - * This lets users paste multiple JSON objects without wrapping them in an - * array, e.g.: + * Supports: + * - Standard JSON (objects, arrays, and primitives) + * - JSON Lines (NDJSON), where each non-empty line is a valid JSON value * - * {"key1": "AAA"} - * {"key1": "BBB"} - * - * Standard JSON (an object or array) is parsed first and returned unchanged. - * Otherwise each non-empty line must be a valid JSON value, and the values are - * returned as an array. A single line that is not valid JSON is reported as a - * plain JSON error rather than being misread as NDJSON. - * - * @param input - Raw text to parse - * @returns The parsed JSON value, or an array of values when NDJSON is detected - * @throws SyntaxError when the input is neither valid JSON nor valid NDJSON - * - * @example - * parseJsonOrNdjson('{"a":1}\n{"a":2}') // → [{ a: 1 }, { a: 2 }] + * @param input - The JSON string to parse. + * @returns The parsed JSON value, or an array of parsed values for JSON Lines input. + * Returns an empty string if the input is empty or whitespace-only. + * @throws {Error} If the input contains invalid JSON. */ -export function parseJsonOrNdjson(input: string): unknown { - const trimmed = input.trim(); - +export function parseJsonInput(input: string): ParsedJson { try { - return JSON.parse(trimmed); - } catch (jsonError) { - const lines = trimmed - .split('\n') - .map((line) => line.trim()) - .filter((line) => line.length > 0); + return JSON.parse(input); + } catch (originalError) { + const lines = input.split(/\r?\n/); - // A single line that already failed JSON.parse is not NDJSON — surface the - // original error instead of masking it. - if (lines.length < 2) { - throw jsonError; + // preserve blank lines numbers + const nonBlankLines: { text: string; lineNumber: number }[] = []; + lines.forEach((line, index) => { + const trimmed = line.trim(); + if (trimmed) { + nonBlankLines.push({ text: trimmed, lineNumber: index + 1 }); + } + }); + + // A single line that fails isn't NDJSON, it's just malformed JSON - + // surface the original error instead of a misleading one. + if (nonBlankLines.length <= 1) { + const reason = + originalError instanceof Error + ? originalError.message + : 'Unknown error'; + throw new Error(`Invalid JSON: ${reason}`); } - const values: unknown[] = []; - for (const line of lines) { + const parsedLines: unknown[] = []; + + for (const { text, lineNumber } of nonBlankLines) { try { - values.push(JSON.parse(line)); - } catch { - // Not valid NDJSON either — report the original JSON parse failure. - throw jsonError; + parsedLines.push(JSON.parse(text)); + } catch (error) { + const reason = + error instanceof Error + ? error.message.replace(/\s*\(line \d+ column \d+\)$/, '') + : 'Unknown error'; + + throw new Error(`Invalid JSON at line ${lineNumber}: ${reason}`); } } - return values; + return parsedLines; } } - /** * Collects all unique keys from an array of row objects, preserving first-encountered order. * Handles sparse rows where different rows may have different keys. @@ -68,8 +78,11 @@ export function getJsonHeaders( if (typeof input === 'string') { try { - const parsed = JSON.parse(input); - rows = Array.isArray(parsed) ? parsed : [parsed]; + const parsed = parseJsonInput(input); + rows = (Array.isArray(parsed) ? parsed : [parsed]) as Record< + string, + string + >[]; } catch { return []; } @@ -79,7 +92,11 @@ export function getJsonHeaders( return Array.from( rows.reduce>((set, row) => { - Object.keys(row).forEach((key) => set.add(key)); + // Skip anything that isn't a plain object (null, arrays, strings, etc.) + // to avoid crashing or pulling in bogus "headers" from those values. + if (row && typeof row === 'object' && !Array.isArray(row)) { + Object.keys(row).forEach((key) => set.add(key)); + } return set; }, new Set()) ); From 8e5af48da5ff5e1f3064eb98786063abb79abb25 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 01:47:06 +0200 Subject: [PATCH 03/12] chore: try catch block removed --- src/pages/tools/json/json-to-csv/service.ts | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/pages/tools/json/json-to-csv/service.ts b/src/pages/tools/json/json-to-csv/service.ts index 529773e0..a496dc86 100644 --- a/src/pages/tools/json/json-to-csv/service.ts +++ b/src/pages/tools/json/json-to-csv/service.ts @@ -1,5 +1,5 @@ import { InitialValuesType } from './types'; -import { getJsonHeaders, parseJsonOrNdjson } from 'utils/json'; +import { getJsonHeaders, parseJsonInput } from 'utils/json'; /** * Recursively flattens any JSON value into a flat object. @@ -84,13 +84,7 @@ export function convertJsonToCsv( if (!delimiter) throw new Error('No CSV delimiter.'); - let parsed: unknown; - - try { - parsed = parseJsonOrNdjson(input); - } catch { - throw new Error('Invalid JSON input.'); - } + const parsed = parseJsonInput(input); const rows = flattenToRows(parsed).filter( (row) => Object.keys(row).length > 0 From 10c06f4df5da2e70d0a1e370f365bece2a94a3ba Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 01:47:38 +0200 Subject: [PATCH 04/12] chore: rewritten test case to handle changes --- src/pages/tools/json/json-to-csv/service.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/pages/tools/json/json-to-csv/service.test.ts b/src/pages/tools/json/json-to-csv/service.test.ts index 8370a87d..73b8fdcc 100644 --- a/src/pages/tools/json/json-to-csv/service.test.ts +++ b/src/pages/tools/json/json-to-csv/service.test.ts @@ -152,8 +152,12 @@ describe('convertJsonToCsv', () => { describe('errors', () => { it('throws on invalid JSON', () => { + // A single malformed line isn't NDJSON, so parseJsonInput re-throws + // its own "Invalid JSON: " error (the text itself + // comes from the JS engine's JSON.parse and varies across engines, + // so we only assert on the stable prefix). expect(() => convertJsonToCsv('invalid json', defaultOptions)).toThrow( - 'Invalid JSON input.' + /^Invalid JSON: / ); }); @@ -196,10 +200,12 @@ describe('convertJsonToCsv', () => { }); it('still throws when one NDJSON line is not valid JSON', () => { + // Two non-blank lines triggers the NDJSON path; the failing line's + // 1-based line number (2) is reported alongside the parse error. const input = '{"a": 1}\nnot json'; expect(() => convertJsonToCsv(input, defaultOptions)).toThrow( - 'Invalid JSON input.' + /^Invalid JSON at line 2: / ); }); }); From 21a2f43a1bb5cceefe86a1d234f94a2cdf14e18a Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 01:49:57 +0200 Subject: [PATCH 05/12] chore: error formatting --- src/pages/tools/json/json-to-csv/index.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/pages/tools/json/json-to-csv/index.tsx b/src/pages/tools/json/json-to-csv/index.tsx index 0ac36ed8..4f5f566e 100644 --- a/src/pages/tools/json/json-to-csv/index.tsx +++ b/src/pages/tools/json/json-to-csv/index.tsx @@ -83,9 +83,7 @@ export default function JsonToCsv({ title }: ToolComponentProps) { setResult(csvResult); } catch (error) { setResult( - `Error: ${ - error instanceof Error ? error.message : 'Invalid JSON format' - }` + ` ${error instanceof Error ? error.message : 'Invalid JSON format'}` ); } } From 5c71fb126d559c4c5dfc6a3feea8dd5bae156c20 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 02:03:21 +0200 Subject: [PATCH 06/12] chore: update validate json service to handle JSONL --- src/pages/tools/json/validateJson/service.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/pages/tools/json/validateJson/service.ts b/src/pages/tools/json/validateJson/service.ts index 2d53367e..3012c295 100644 --- a/src/pages/tools/json/validateJson/service.ts +++ b/src/pages/tools/json/validateJson/service.ts @@ -1,11 +1,13 @@ +import { parseJsonInput } from '@utils/json'; + export const validateJson = ( input: string ): { valid: boolean; error?: string } => { try { - JSON.parse(input); + parseJsonInput(input); return { valid: true }; } catch (error) { - if (error instanceof SyntaxError) { + if (error instanceof Error) { return { valid: false, error: error.message }; } return { valid: false, error: 'Unknown error occurred' }; From d75f108ab4559bf6560f6f292c8a2f141cb1ac95 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 02:19:21 +0200 Subject: [PATCH 07/12] chore: updated util to specify the json format --- src/pages/tools/json/json-to-csv/service.ts | 6 ++---- src/utils/json.ts | 20 ++++++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/pages/tools/json/json-to-csv/service.ts b/src/pages/tools/json/json-to-csv/service.ts index a496dc86..7a2618cb 100644 --- a/src/pages/tools/json/json-to-csv/service.ts +++ b/src/pages/tools/json/json-to-csv/service.ts @@ -84,11 +84,9 @@ export function convertJsonToCsv( if (!delimiter) throw new Error('No CSV delimiter.'); - const parsed = parseJsonInput(input); + const { data } = parseJsonInput(input); - const rows = flattenToRows(parsed).filter( - (row) => Object.keys(row).length > 0 - ); + const rows = flattenToRows(data).filter((row) => Object.keys(row).length > 0); if (rows.length === 0) { throw new Error('No data found in the provided JSON.'); diff --git a/src/utils/json.ts b/src/utils/json.ts index f9722cea..f1020007 100644 --- a/src/utils/json.ts +++ b/src/utils/json.ts @@ -6,6 +6,13 @@ export type ParsedJson = | boolean | null; +export type JsonFormat = 'json' | 'jsonl'; + +export interface ParseJsonResult { + data: ParsedJson; + format: JsonFormat; +} + /** * Parses a JSON string into its JavaScript representation. * @@ -18,9 +25,9 @@ export type ParsedJson = * Returns an empty string if the input is empty or whitespace-only. * @throws {Error} If the input contains invalid JSON. */ -export function parseJsonInput(input: string): ParsedJson { +export function parseJsonInput(input: string): ParseJsonResult { try { - return JSON.parse(input); + return { data: JSON.parse(input), format: 'json' }; } catch (originalError) { const lines = input.split(/\r?\n/); @@ -58,7 +65,7 @@ export function parseJsonInput(input: string): ParsedJson { } } - return parsedLines; + return { data: parsedLines, format: 'jsonl' }; } } /** @@ -78,11 +85,8 @@ export function getJsonHeaders( if (typeof input === 'string') { try { - const parsed = parseJsonInput(input); - rows = (Array.isArray(parsed) ? parsed : [parsed]) as Record< - string, - string - >[]; + const { data } = parseJsonInput(input); + rows = (Array.isArray(data) ? data : [data]) as Record[]; } catch { return []; } From 094ed16a39897057082b3d3e206ce3c786d36c32 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 02:23:31 +0200 Subject: [PATCH 08/12] chore: initial error on validate json handling --- src/pages/tools/json/validateJson/index.tsx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/pages/tools/json/validateJson/index.tsx b/src/pages/tools/json/validateJson/index.tsx index ca8ec1fe..b66c3e7d 100644 --- a/src/pages/tools/json/validateJson/index.tsx +++ b/src/pages/tools/json/validateJson/index.tsx @@ -52,12 +52,14 @@ export default function ValidateJson({ title }: ToolComponentProps) { const [result, setResult] = useState(''); const compute = (options: any, input: string) => { - const { valid, error } = validateJson(input); + if (input) { + const { valid, error } = validateJson(input); - if (valid) { - setResult(t('validateJson.validJson')); - } else { - setResult(t('validateJson.invalidJson', { error })); + if (valid) { + setResult(t('validateJson.validJson')); + } else { + setResult(t('validateJson.invalidJson', { error })); + } } }; From d57017ddac330e6923abffa716dbbe08a457c9f9 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 02:52:43 +0200 Subject: [PATCH 09/12] chore: updated sort json to handle Jsonl --- src/pages/tools/json/sort/index.tsx | 16 ++++++-- src/pages/tools/json/sort/service.ts | 58 +++++++++++++++++----------- src/pages/tools/json/sort/types.ts | 7 ++++ 3 files changed, 56 insertions(+), 25 deletions(-) diff --git a/src/pages/tools/json/sort/index.tsx b/src/pages/tools/json/sort/index.tsx index 85677ff0..0a337d89 100644 --- a/src/pages/tools/json/sort/index.tsx +++ b/src/pages/tools/json/sort/index.tsx @@ -61,10 +61,20 @@ export default function SortJson({ const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); + const [format, setFormat] = useState('json'); const compute = (values: InitialValuesType, input: string) => { - if (!input.trim()) return; - setResult(sortJson(input, values)); + if (input) { + try { + const { result, format } = sortJson(input, values); + setResult(result); + setFormat(format); + } catch (error) { + setResult( + ` ${error instanceof Error ? error.message : 'Invalid JSON format'}` + ); + } + } }; const keys = getJsonHeaders(input); @@ -148,7 +158,7 @@ export default function SortJson({ } initialValues={initialValues} diff --git a/src/pages/tools/json/sort/service.ts b/src/pages/tools/json/sort/service.ts index 1a745390..136451ac 100644 --- a/src/pages/tools/json/sort/service.ts +++ b/src/pages/tools/json/sort/service.ts @@ -1,4 +1,5 @@ -import { order, InitialValuesType } from './types'; +import { order, InitialValuesType, SortJsonResult } from './types'; +import { parseJsonInput, JsonFormat } from '@utils/json'; const sortObject = ( obj: Record, @@ -13,37 +14,50 @@ const sortObject = ( return result; }; -export const sortJson = (text: string, options: InitialValuesType): string => { - const { mode, order, key } = options; - let parsed; - try { - parsed = JSON.parse(text); - } catch (e) { - throw new Error('Invalid JSON string'); +/** + * Serializes the final value back to a string, matching the shape of the + * original input: NDJSON (one compact JSON value per line) for 'jsonl' + * input, pretty-printed JSON otherwise. + */ +const serialize = (value: unknown, format: JsonFormat): string => { + if (format === 'jsonl' && Array.isArray(value)) { + return value.map((item) => JSON.stringify(item)).join('\n'); } + return JSON.stringify(value, null, 2); +}; + +export const sortJson = ( + text: string, + options: InitialValuesType +): SortJsonResult => { + const { mode, order, key } = options; + + const { data, format } = parseJsonInput(text); if (mode === 'key') { - if (Array.isArray(parsed)) { - if (parsed.length === 0) throw new Error('Array is empty'); - return JSON.stringify( - parsed.map((item) => sortObject(item, order)), - null, - 2 + if (Array.isArray(data)) { + if (data.length === 0) throw new Error('Array is empty'); + const sortedArray = data.map((item) => + sortObject(item as Record, order) ); + return { result: serialize(sortedArray, format), format }; } - if (typeof parsed !== 'object' || parsed === null) { + if (typeof data !== 'object' || data === null) { throw new Error('Input must be a JSON object or array of objects'); } - return JSON.stringify(sortObject(parsed, order), null, 2); + return { result: serialize(sortObject(data, order), format), format }; } // value mode - if (!Array.isArray(parsed)) throw new Error('Input must be a JSON array'); - if (parsed.length === 0) throw new Error('Array is empty'); + if (!Array.isArray(data)) throw new Error('Input must be a JSON array'); + if (data.length === 0) throw new Error('Array is empty'); - const sorted = [...parsed].sort((a, b) => { - const aVal = a[key]; - const bVal = b[key]; + const sorted = [...data].sort((a, b) => { + const aRow = a as Record; + const bRow = b as Record; + const aVal = aRow[key]; + const bVal = bRow[key]; + if (aVal == null && bVal == null) return 0; if (aVal == null) return 1; if (bVal == null) return -1; if (typeof aVal === 'object' && typeof bVal === 'object') { @@ -58,5 +72,5 @@ export const sortJson = (text: string, options: InitialValuesType): string => { return 0; }); - return JSON.stringify(sorted, null, 2); + return { result: serialize(sorted, format), format }; }; diff --git a/src/pages/tools/json/sort/types.ts b/src/pages/tools/json/sort/types.ts index a17a255f..bc330fbb 100644 --- a/src/pages/tools/json/sort/types.ts +++ b/src/pages/tools/json/sort/types.ts @@ -1,3 +1,5 @@ +import { JsonFormat } from '@utils/json'; + export type mode = 'value' | 'key'; export type order = 'asc' | 'desc'; @@ -6,3 +8,8 @@ export type InitialValuesType = { key: string; order: order; }; + +export interface SortJsonResult { + result: string; + format: JsonFormat; +} From 63bd26009d6aa7a3264d071cd6fabd23193e8208 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 03:28:50 +0200 Subject: [PATCH 10/12] chore: updated minify json to handle Jsonl --- src/pages/tools/json/minify/index.tsx | 16 ++++++++++++++-- src/pages/tools/json/minify/service.ts | 23 ++++++++++++++++------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/pages/tools/json/minify/index.tsx b/src/pages/tools/json/minify/index.tsx index 379d0f37..954e79cc 100644 --- a/src/pages/tools/json/minify/index.tsx +++ b/src/pages/tools/json/minify/index.tsx @@ -6,6 +6,7 @@ import { minifyJson } from './service'; import { CardExampleType } from '@components/examples/ToolExamples'; import { ToolComponentProps } from '@tools/defineTool'; import { useTranslation } from 'react-i18next'; +import { JsonFormat } from '@utils/json'; type InitialValuesType = Record; @@ -51,9 +52,20 @@ export default function MinifyJson({ title }: ToolComponentProps) { const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); + const [format, setFormat] = useState('json'); const compute = (_: InitialValuesType, input: string) => { - if (input) setResult(minifyJson(input)); + if (input) { + try { + const { result, format } = minifyJson(input); + setResult(result); + setFormat(format); + } catch (error) { + setResult( + ` ${error instanceof Error ? error.message : 'Invalid JSON format'}` + ); + } + } }; return ( @@ -71,7 +83,7 @@ export default function MinifyJson({ title }: ToolComponentProps) { } initialValues={initialValues} diff --git a/src/pages/tools/json/minify/service.ts b/src/pages/tools/json/minify/service.ts index a5bbc50d..a3f133de 100644 --- a/src/pages/tools/json/minify/service.ts +++ b/src/pages/tools/json/minify/service.ts @@ -1,10 +1,19 @@ -export const minifyJson = (text: string) => { - let parsedJson; - try { - parsedJson = JSON.parse(text); - } catch (e) { - throw new Error('Invalid JSON string'); +import { parseJsonInput, JsonFormat } from '@utils/json'; + +export interface MinifyJsonResult { + result: string; + format: JsonFormat; +} + +export const minifyJson = (text: string): MinifyJsonResult => { + const { data, format } = parseJsonInput(text); + + if (format === 'jsonl' && Array.isArray(data)) { + return { + result: data.map((item) => JSON.stringify(item)).join('\n'), + format + }; } - return JSON.stringify(parsedJson); + return { result: JSON.stringify(data), format }; }; From 6584d7e22653e98c0d34a0542ae73214dee7c000 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 03:30:44 +0200 Subject: [PATCH 11/12] chore: safe typing --- src/pages/tools/json/sort/index.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pages/tools/json/sort/index.tsx b/src/pages/tools/json/sort/index.tsx index 0a337d89..185daccf 100644 --- a/src/pages/tools/json/sort/index.tsx +++ b/src/pages/tools/json/sort/index.tsx @@ -11,6 +11,7 @@ import { InitialValuesType } from './types'; import { GetGroupsType } from '@components/options/ToolOptions'; import { getJsonHeaders } from '@utils/json'; import { useTranslation } from 'react-i18next'; +import { JsonFormat } from '@utils/json'; const initialValues: InitialValuesType = { mode: 'value', @@ -61,7 +62,7 @@ export default function SortJson({ const { t } = useTranslation('json'); const [input, setInput] = useState(''); const [result, setResult] = useState(''); - const [format, setFormat] = useState('json'); + const [format, setFormat] = useState('json'); const compute = (values: InitialValuesType, input: string) => { if (input) { From 876608c03282b8a7036a89f44728100eae5e6752 Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 26 Jul 2026 04:13:56 +0200 Subject: [PATCH 12/12] chore: (fix) tsv to json (minify) --- src/pages/tools/csv/tsv-to-json/service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/tools/csv/tsv-to-json/service.ts b/src/pages/tools/csv/tsv-to-json/service.ts index dadd40a2..375857ce 100644 --- a/src/pages/tools/csv/tsv-to-json/service.ts +++ b/src/pages/tools/csv/tsv-to-json/service.ts @@ -48,7 +48,7 @@ export function convertTsvToJson( } return options.indentationType === 'none' - ? minifyJson(JSON.stringify(result)) + ? minifyJson(JSON.stringify(result)).result : beautifyJson( JSON.stringify(result), options.indentationType,