mirror of
https://github.com/iib0011/omni-tools.git
synced 2026-11-29 00:29:43 +03:00
Merge pull request #385 from arimu1/feat/353-ndjson-json-to-csv
feat(json-to-csv): accept NDJSON / multiple objects without an array wrapper
This commit is contained in:
12 files changed
+221
-60
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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'}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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: <reason>" error (the <reason> 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: /
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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.');
|
||||
|
||||
@@ -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<string, never>;
|
||||
|
||||
@@ -51,9 +52,20 @@ export default function MinifyJson({ title }: ToolComponentProps) {
|
||||
const { t } = useTranslation('json');
|
||||
const [input, setInput] = useState<string>('');
|
||||
const [result, setResult] = useState<string>('');
|
||||
const [format, setFormat] = useState<JsonFormat>('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) {
|
||||
<ToolTextResult
|
||||
title={t('minify.resultTitle')}
|
||||
value={result}
|
||||
extension={'json'}
|
||||
extension={format}
|
||||
/>
|
||||
}
|
||||
initialValues={initialValues}
|
||||
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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<string>('');
|
||||
const [result, setResult] = useState<string>('');
|
||||
const [format, setFormat] = useState<JsonFormat>('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({
|
||||
<ToolTextResult
|
||||
title={t('sortJson.resultTitle')}
|
||||
value={result}
|
||||
extension={'json'}
|
||||
extension={format}
|
||||
/>
|
||||
}
|
||||
initialValues={initialValues}
|
||||
|
||||
@@ -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<string, unknown>,
|
||||
@@ -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<string, unknown>, 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<string, unknown>;
|
||||
const bRow = b as Record<string, unknown>;
|
||||
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 };
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
@@ -52,12 +52,14 @@ export default function ValidateJson({ title }: ToolComponentProps) {
|
||||
const [result, setResult] = useState<string>('');
|
||||
|
||||
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 }));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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' };
|
||||
|
||||
+77
-3
@@ -1,3 +1,73 @@
|
||||
export type ParsedJson =
|
||||
| Record<string, unknown>
|
||||
| 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<string, string>[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
@@ -26,7 +96,11 @@ export function getJsonHeaders(
|
||||
|
||||
return Array.from(
|
||||
rows.reduce<Set<string>>((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())
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user