PowerShell에서 해시 테이블을 JSON으로 올바르게 변환하려면 어떻게 해야 합니까?
PowerShell을 사용하여 다음 메시지를 보냅니다.POST
에의 요청.REST API
요청 본문은 다음과 같습니다.
{
"title": "game result",
"attachments": [{
"image_url": "http://contoso/",
"title": "good work!"
},
{
"fields": [{
"title": "score",
"value": "100"
},
{
"title": "bonus",
"value": "50"
}
]
}
]
}
이제 다음 PowerShell 스크립트가 잘못된 출력을 생성합니다.
$fields = @(@{title='score'; value='100'},@{title='bonus'; value='10'})
$fieldsWrap = @{fields=$fields}
#$fieldsWrap | ConvertTo-Json
$attachments = @(@{title='good work!';image_url='http://contoso'},$fieldsWrap)
$body = @{title='game results';attachments=$attachments}
$json = $body | ConvertTo-Json
$json
라인 3(주석이 없는 경우)은 올바른 출력을 생성하지만 라인 7은 다음을 생성합니다.
{
"attachments": [{
"image_url": "http://contoso",
"title": "good work!"
},
{
"fields": "System.Collections.Hashtable System.Collections.Hashtable"
}
],
"title": "game result"
}
그것은 분명히 그것의 유형 이름을 적습니다.HashTable
어느 것이 기본값입니까?ToString()
내 생각에는 실행.
올바른 출력을 얻으려면 어떻게 해야 합니까?
ConvertTo-Json cmdlet에는 다음이 있습니다.-depth
매개 변수:
JSON 표현에 포함되는 포함된 객체의 수준 수를 지정합니다.기본값은 2입니다.
따라서 이 값을 늘려야 합니다.
$body | ConvertTo-Json -Depth 4
이렇게 하면 원하는 JSON 출력이 제공됩니다.
@{
title = "game result"
attachments = @(
@{
image_url = "http://contoso/"
title = "good work!"
},
@{
fields = @(
@{
title = "score"
value = "100"
},
@{
title = "bonus"
value = "50"
}
)
}
)
} | ConvertTo-Json -Depth 4
하지만 마틴 브랜들의 조언이 없었다면 일하지 않았을 것입니다. :)
언급URL : https://stackoverflow.com/questions/38012564/how-do-i-correctly-convert-a-hashtable-to-json-in-powershell
'programing' 카테고리의 다른 글
MySQL SELECT 쿼리 문자열 일치 (0) | 2023.09.01 |
---|---|
스프링 부트 동적 쿼리 (0) | 2023.09.01 |
mariadb 테이블에서 정확하게 일치하는 행만 가져오는 중 (0) | 2023.09.01 |
Cocoapods + 'x'에 대한 기본 모듈을 로드할 수 없습니다. (0) | 2023.08.27 |
도커 합성을 통해 항상 새로운 이미지에서 컨테이너를 다시 생성하는 방법은 무엇입니까? (0) | 2023.08.27 |