programing

powershell 3에서 json을 예쁘게 하다

javamemo 2023. 3. 1. 08:47
반응형

powershell 3에서 json을 예쁘게 하다

표준 json 문자열 값 지정:

$jsonString = '{ "baz": "quuz", "cow": [ "moo", "cud" ], "foo": "bar" }'

어떻게 하면 이 모든 것을 새로운 라인으로 예쁘게 만들 수 있을까요? 가능하면 브루트 포스 정규식을 사용하지 않는 것이 좋습니다.

지금까지 발견한 가장 간단한 방법은 다음과 같습니다.

$jsonString | ConvertFrom-Json | ConvertTo-Json 

하지만, 그건 좀 바보 같아.

저는 좋아요.괄호는 파이프 연결 전에 get-content가 수행되었는지 확인합니다.converto-json의 기본 깊이는 2이며, 이는 종종 너무 낮습니다.

function pjson ($jsonfile) {
  (get-content $jsonfile) | convertfrom-json | convertto-json -depth 100 | 
    set-content $jsonfile
}

가장 간단한 방법, 즉 내장된 PowerShell 기능을 사용하고 싶지 않은 경우| ConvertFrom-Json | ConvertTo-JsonJSON.net 를 사용하는 다른 방법이 있습니다.

# http://james.newtonking.com/projects/json-net.aspx
Add-Type -Path "DRIVE:\path\to\Newtonsoft.Json.dll"

$jsonString = '{ "baz": "quuz", "cow": [ "moo", "cud" ], "foo": "bar" }'
[Newtonsoft.Json.Linq.JObject]::Parse($jsonString).ToString()

이걸 프로필에 넣었어요

function PrettyPrintJson {
    param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        $json
    )
    $json | ConvertFrom-Json | ConvertTo-Json -Depth 100
}

파이프와 함께 작동하며 자동 완성할 수 있으므로 최소한 타이핑이 다소 줄어듭니다.

cat .\file.json | PrettyPrintJson
curl https://api.twitter.com/1.1/statuses/user_timeline.json | PrettyPrintJson

@JS2010의 회답에, 특정의 문자를 이스케이프 해, 한층 더 출력을 정리하는 논리를 추가했습니다.괄호 안에 열쇠가 있는 것 같고-depth디폴트인 5를 넘어서는 디테일을 잃어버릴 수 있기 때문에 큰 문제라고 생각합니다.

function Format-Json ($JSON)
{
    $PrettifiedJSON = ($JSON) | convertfrom-json | convertto-json -depth 100 | ForEach-Object { [System.Text.RegularExpressions.Regex]::Unescape($_) }
    $PrettifiedJSON
}

당신이 찾고 있는 것은 다음과 같습니다.

$jsonString = @{ 
'baz' = 'quuz'
'cow'= "moo, cud"
'foo'= "bar" 
}
$jsonString|ConvertTo-Json

이 출력을 생성합니다.

{
    "baz":  "quuz",
    "cow":  "moo, cud",
    "foo":  "bar"
}

참고 사항 추가 소 값을 배열하여 "예비"할 수도 있습니다.

 $jsonString = @{ 
    'baz' = 'quuz'
    'cow'= @("moo"; "cud")
    'foo'= "bar" 
    }

출력:

{
    "baz":  "quuz",
    "cow":  [
                "moo",
                "cud"
            ],
    "foo":  "bar"
}

언급URL : https://stackoverflow.com/questions/24789365/prettify-json-in-powershell-3

반응형