How can I convert a hastable to a json string in powershell?

爱⌒轻易说出口 提交于 2019-12-05 10:51:31

I adapted the script from here as below:

$testhash = @{
    Name = 'John Doe'
    Age = 10
    Amount = 10.1
    MixedItems = (1,2,3,"a")
    NestedHash = @{
        nestedkey = "nextedvalue"
    }
}

function Read-Stream {
PARAM(
   [Parameter(Position=0,ValueFromPipeline=$true)]$Stream
)
process {
   $bytes = $Stream.ToArray()
   [System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
}}

function New-Json {
[CmdletBinding()]
param([Parameter(ValueFromPipeline=$true)][HashTable]$InputObject) 
begin { 
   $ser = @{}
   $jsona = @()
}
process {
   $jsoni = 
   foreach($input in $InputObject.GetEnumerator() | Where { $_.Value } ) {
      if($input.Value -is [Hashtable]) {
         '"'+$input.Key+'": ' + (New-JSon $input.Value)
      } else {
         $type = $input.Value.GetType()
         if(!$Ser.ContainsKey($Type)) {
            $Ser.($Type) = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $type
         }
         $stream = New-Object System.IO.MemoryStream
         $Ser.($Type).WriteObject( $stream, $Input.Value )
         '"'+$input.Key+'": ' + (Read-Stream $stream)
      }
   }

   $jsona += "{`n" +($jsoni -join ",`n")+ "`n}"
}
end { 
   if($jsona.Count -gt 1) {
      "[$($jsona -join ",`n")]" 
   } else {
      $jsona
   }
}}

$testHash | New-Json

Ok, so manojlds answered for v2 so I'll just throw up the v3 equivalent here:

PS> @{name="oisin"; age=37} | convertto-json
{
    "age":  37,
    "name":  "oisin"
}

Quite a bit cleaner, right?

PowerShell 3.0 CTP2: http://www.microsoft.com/download/en/details.aspx?id=27548

A nice clean one-liner.

ConvertTo-Json ([System.Management.Automatio.PSObject] $testhash)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!