#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 --input data.json [--output data.csv] [--ndjson] [--force]" } input="" output="" ndjson=0 force=0 while [[ $# -gt 0 ]]; do case "$1" in --input) input="${2:-}"; shift 2 ;; --output) output="${2:-}"; shift 2 ;; --ndjson) ndjson=1; shift ;; --force) force=1; shift ;; -h|--help) usage; exit 0 ;; *) echo "Неизвестный аргумент: $1" >&2; usage >&2; exit 2 ;; esac done if [[ -z "$input" || ! -f "$input" ]]; then echo "Укажите существующий JSON-файл через --input" >&2 exit 2 fi if ! command -v jq >/dev/null 2>&1; then echo "Не найден jq" >&2 exit 2 fi if [[ -n "$output" && -e "$output" && "$force" -eq 0 ]]; then echo "Файл уже существует: $output. Добавьте --force." >&2 exit 2 fi if [[ -n "$output" && "$output" == "$input" ]]; then echo "Выходной файл совпадает с входным" >&2 exit 2 fi filter=' if type != "array" then error("JSON root must be an array of objects") else . end | ((map(keys) | add // []) | unique) as $keys | $keys, (.[] | [ .[$keys[]] | if . == null then "" elif type == "string" then . else tostring end ]) | @csv ' tmp="$(mktemp)" trap 'rm -f -- "$tmp"' EXIT if [[ "$ndjson" -eq 1 ]]; then jq -s -r "$filter" "$input" > "$tmp" else jq -r "$filter" "$input" > "$tmp" fi if [[ -n "$output" ]]; then mkdir -p -- "$(dirname -- "$output")" mv -- "$tmp" "$output" trap - EXIT echo "CSV сохранён: $output" else cat "$tmp" fi