programing

PowerShell에서 해시 테이블을 JSON으로 올바르게 변환하려면 어떻게 해야 합니까?

javajsp 2023. 9. 1. 20:34

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