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, 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'}` ); } } 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..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: / ); }); @@ -169,4 +173,40 @@ 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', () => { + // 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 at line 2: / + ); + }); + }); }); diff --git a/src/pages/tools/json/json-to-csv/service.ts b/src/pages/tools/json/json-to-csv/service.ts index 33ddeb4e..7a2618cb 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, parseJsonInput } from 'utils/json'; /** * Recursively flattens any JSON value into a flat object. @@ -84,17 +84,9 @@ export function convertJsonToCsv( if (!delimiter) throw new Error('No CSV delimiter.'); - let parsed: unknown; + const { data } = parseJsonInput(input); - try { - parsed = JSON.parse(input); - } catch { - throw new Error('Invalid JSON 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/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 }; }; diff --git a/src/pages/tools/json/sort/index.tsx b/src/pages/tools/json/sort/index.tsx index 85677ff0..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,10 +62,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 +159,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; +} 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 })); + } } }; 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' }; diff --git a/src/utils/json.ts b/src/utils/json.ts index c243ab37..f1020007 100644 --- a/src/utils/json.ts +++ b/src/utils/json.ts @@ -1,3 +1,73 @@ +export type ParsedJson = + | Record + | unknown[] + | string + | number + | boolean + | null; + +export type JsonFormat = 'json' | 'jsonl'; + +export interface ParseJsonResult { + data: ParsedJson; + format: JsonFormat; +} + +/** + * Parses a JSON string into its JavaScript representation. + * + * Supports: + * - Standard JSON (objects, arrays, and primitives) + * - JSON Lines (NDJSON), where each non-empty line is a valid JSON value + * + * @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 parseJsonInput(input: string): ParseJsonResult { + try { + return { data: JSON.parse(input), format: 'json' }; + } catch (originalError) { + const lines = input.split(/\r?\n/); + + // 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 parsedLines: unknown[] = []; + + for (const { text, lineNumber } of nonBlankLines) { + try { + 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 { data: parsedLines, format: 'jsonl' }; + } +} /** * Collects all unique keys from an array of row objects, preserving first-encountered order. * Handles sparse rows where different rows may have different keys. @@ -15,8 +85,8 @@ export function getJsonHeaders( if (typeof input === 'string') { try { - const parsed = JSON.parse(input); - rows = Array.isArray(parsed) ? parsed : [parsed]; + const { data } = parseJsonInput(input); + rows = (Array.isArray(data) ? data : [data]) as Record[]; } catch { return []; } @@ -26,7 +96,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()) );