0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PowerShellでJSON文字列整形/JSON文字列に戻す

0
Posted at

json-format.ps1

param (
    [Parameter(Mandatory = $true)]
    [string]$InputFile,

    [Parameter(Mandatory = $true)]
    [string]$OutputFile,

    # JSON整形 / JSON文字列
    [ValidateSet("json_format", "json_string")]
    [string]$Mode = "json_format",

    # ネスト深さ対策
    [int]$Depth = 100
)

if (-not (Test-Path $InputFile)) {
    Write-Error "Input file not found: $InputFile"
    exit 1
}

try {
    $json = Get-Content $InputFile -Raw
    $obj  = $json | ConvertFrom-Json

    if ($Mode -eq "json_format") {
        $out = $obj | ConvertTo-Json -Depth $Depth
    } else {
        $out = $obj | ConvertTo-Json -Depth $Depth -Compress
    }

    Set-Content $OutputFile $out
}
catch {
    Write-Error "JSON parse failed: $($_.Exception.Message)"
    exit 2
}

input.json

{ "test": "aaaa","test2":"bbbb"}

実行

powershell -File json-format.ps1 input.json JSON整形.json json_format
powershell -File json-format.ps1 pretty.json JSON文字列.json json_string

JSON整形のアウトプット

{
    "test":  "aaaa",
    "test2":  "bbbb"
}

JSON文字列のアウトプット

{ "test": "aaaa","test2":"bbbb"}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?