在Powershell中转换为JSON时如何更改选项卡宽度 [英] How to change tab width when converting to JSON in Powershell

查看:98
本文介绍了在Powershell中转换为JSON时如何更改选项卡宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Powershell中创建一个JSON,我想在构建它时设置自定义选项卡的宽度(而不是默认的4个空格,我只希望设置2个空格).

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).

我这样做是因为:

  • 实际JSON(不是下面的示例中显示的JSON)非常大(超过100k行),如果不进行归档,则它的大小非常大;如果我减小标签宽度,则尺寸会显着减小.
  • 实际JSON的深度超过5个节点!
  • 我无法使用-Co​​mpress,因为JSON必须易于阅读
  • 是的,我同意,如果已存档,它的大小会大大减小,但我也需要将其存档.

示例代码:

$object = New-Object PSObject
Add-Member -InputObject $object -MemberType NoteProperty -Name Phone -Value "SomePhone"
Add-Member -InputObject $object -MemberType NoteProperty -Name Description -Value "Lorem ipsum dolor.."
Add-Member -InputObject $object -MemberType NoteProperty -Name Price -Value 99.99

$object | ConvertTo-Json

制表符宽度= 4个空格字符的结果.

Result with tab width = 4 white space characters.

{
    "Phone":  "SomePhone",
    "Description":  "Lorem ipsum dolor..",
    "Price":  99.99
}

我尝试过压缩,但是它无法控制压缩级别(积极压缩应该如何)

I tried compression but it doesn't give control over compression level (how agressive compression should be)

$object | ConvertTo-Json -Compress

结果显然很压缩.

Result compressed, obviously.

{"Phone":"SomePhone","Description":"Lorem ipsum dolor..","Price":99.99}

我要实现的目标:制表符宽度= 2个空格字符的结果.

{
  "Phone":  "SomePhone",
  "Description":  "Lorem ipsum dolor..",
  "Price":  99.99
}

到目前为止,我尝试过的是下面的伪代码.我仍然处于循环中.请让我离开那里:)

What I've tried so far is in the pseudo code below. I'm still in the loop. Please get me out of there :)

while (1) {
    Google, StackOverflow
    Try Stuff found 
    Tweak stuff found

    if (Correct answer) {
        break
    }
}

推荐答案

以下代码将缩进的大小减半:

The following code will halve the size of indent:

$json = @"
{
    "Phone":  "SomePhone",
    "Description":  "Lorem ipsum dolor..",
    "Price":  99.99
}
"@

($json -split '\r\n' |
% {
  $line = $_
  if ($_ -match '^ +') {
    $len  = $Matches[0].Length / 2
    $line = ' ' * $len + $line.TrimStart()
  }
  $line
}) -join "`r`n"

这篇关于在Powershell中转换为JSON时如何更改选项卡宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆