How to change tab width when converting to JSON in Powershell

前端 未结 4 1248
执笔经年
执笔经年 2021-02-05 12:21

I am creating a JSON in Powershell and I want to set a custom tab width when building it (instead of the default 4 white spaces I want to set only 2 white spaces).

I am

4条回答
  •  走了就别回头了
    2021-02-05 13:21

    Because the PowerShell's ConvertTo-Json produces non-deterministic indentation, the current answers will not produce JSON that has exactly two spaces for each depth in the data structure.

    To get each level of nested data indented exactly two spaces more than the enclosing level requires rebuilding the indentation. (For what it's worth, looks like this was fixed in PowerShell 6)

    After writing up my own solution, I found an almost identical one on GitHub, from Facebook's Daniel Lo Nigro (Daniel15) here. His is a PowerShell function that can take piped input. (I made the regex matches a bit more specific to reduce the likelihood of unintentional matching data.)

    # Formats JSON in a nicer format than the built-in ConvertTo-Json does.
    function Format-Json([Parameter(Mandatory, ValueFromPipeline)][String] $json) {
        $indent = 0;
        ($json -Split "`n" | % {
            if ($_ -match '[\}\]]\s*,?\s*$') {
                # This line ends with ] or }, decrement the indentation level
                $indent--
            }
            $line = ('  ' * $indent) + $($_.TrimStart() -replace '":  (["{[])', '": $1' -replace ':  ', ': ')
            if ($_ -match '[\{\[]\s*$') {
                # This line ends with [ or {, increment the indentation level
                $indent++
            }
            $line
        }) -Join "`n"
    }
    

    Usage: $foo | ConvertTo-Json | Format-Json

提交回复
热议问题