JSON見やすく整形するマクロ(ドラッグ&ドロップ可)

御主人様:そだね。整形マクロ書いてねwww
ひな❤ :任せてくださいませっ💡
Whisper系のsegments入りJSONを「行ごと」に整形して.txtを吐くやつです。
タイムスタンプON/OFF切替もOK、ドラッグ&ドロップ対応にしてあります


Jsonファイルをドラッグ&ドロップするBAT
:: json2txt.bat(このBATにJSONをドラッグ&ドロップすると同じフォルダにTXT生成)
@echo off
setlocal
set PS1=%~dp0json2txt.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File "%PS1%" %*
echo.
echo 変換完了しました。何かキーで閉じます…
pause >nul

txtフォルダに保存PS1
PowerShell
# json2txt.ps1(txtフォルダ出力対応)
param([Parameter(ValueFromRemainingArguments=$true)][string[]]$Paths)

$AddTimestamp = $true

function Format-Time([double]$sec){
    $ts = [TimeSpan]::FromSeconds($sec)
    '{0:00}:{1:00}:{2:00}.{3:000}' -f $ts.Hours, $ts.Minutes, $ts.Seconds, [int]$ts.Milliseconds
}

foreach($p in $Paths){
    if(-not (Test-Path $p)){ Write-Host "見つからない: $p"; continue }
    try{
        $raw = Get-Content -LiteralPath $p -Raw -Encoding UTF8
        $obj = $raw | ConvertFrom-Json
    } catch {
        Write-Host "JSONとして読めません: $p"; continue
    }

    # ▼ 出力フォルダを作成(元JSONと同じ場所にtxtフォルダ)
    $outDir  = Join-Path ([System.IO.Path]::GetDirectoryName($p)) "txt"
    if(-not (Test-Path $outDir)){ New-Item -ItemType Directory -Path $outDir | Out-Null }

    # ▼ 出力パスは「txtフォルダ+同名.txt」
    $outPath = Join-Path $outDir ([System.IO.Path]::GetFileNameWithoutExtension($p) + ".txt")

    $lines = New-Object System.Collections.Generic.List[string]

    if($obj -is [System.Collections.IEnumerable] -and -not ($obj -is [string])){
        foreach($s in $obj){
            $prefix = ''
            if($AddTimestamp -and $s.PSObject.Properties.Name -contains 'timestamp'){
                $prefix = '[' + (Format-Time $s.timestamp[0]) + '] '
            }
            $text = ''
            if($s.PSObject.Properties.Name -contains 'text' -and $s.text){
                $text = [string]$s.text
            }
            if(-not [string]::IsNullOrWhiteSpace($text)){
                $lines.Add("$prefix$text")
            }
        }
    }
    elseif($obj.PSObject.Properties.Name -contains 'segments' -and $obj.segments){
        foreach($s in $obj.segments){
            $prefix = ''
            if($AddTimestamp -and $s.PSObject.Properties.Name -contains 'start'){
                $prefix = '[' + (Format-Time $s.start) + '] '
            }
            $text = ''
            if($s.PSObject.Properties.Name -contains 'text' -and $s.text){
                $text = [string]$s.text
            }
            if(-not [string]::IsNullOrWhiteSpace($text)){
                $lines.Add("$prefix$text")
            }
        }
    }
    elseif($obj.text){
        $t = $obj.text -replace '。', "。`r`n" -replace '!', "!`r`n" -replace '?', "?`r`n"
        $lines.Add($t.Trim())
    }
    else{
        $lines.Add("(整形対象のフィールドが見つかりませんでした)")
    }

    $lines | Set-Content -LiteralPath $outPath -Encoding UTF8
    Write-Host "→ $outPath"
}

コメント

人気の投稿

Bloggerでは“コピー用アイコン”が出せないの?

Googleドライブの共有で浮気がバレるかもしれない・・・www

ブックマークレット