PoshCode Logo PowerShell Code Repository

JSON (modification of post by view diff)
View followups from Joel Bennett | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1513"></script>download | new post

Json.psm1 is a first draft of a JSON module. I has a full set of tools for exporting, importing, and converting Json objects. For instance, this actually works (it round trips a bunch of FileInfo objects through JSON, XML, JSON, and back to objects).

ls | Where { !$_.PSIsContainer } | ConvertTo-Json | Convert-JsonToXml | Convert-XmlToJson | ConvertFrom-Json IO.FileInfo[]

However, this module is still very incomplete

  1. #requires -version 2.0
  2. # No help (yet) because I'm still changing and renaming everything every time I mess with this code
  3. Add-Type -Assembly System.ServiceModel.Web, System.Runtime.Serialization
  4. $utf8 = [System.Text.Encoding]::UTF8
  5.  
  6.  
  7. function Convert-JsonToXml
  8. {
  9. PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
  10. BEGIN { $mStream = new-object System.IO.MemoryStream }
  11. PROCESS {
  12.    $json | Write-String -Stream $mStream
  13. }
  14. END {
  15.    $mStream.Position = 0
  16.    $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
  17.    try
  18.    {
  19.       $xml = new-object Xml.XmlDocument
  20.       $xml.Load($jsonReader)
  21.       $xml
  22.    }
  23.    finally
  24.    {
  25.       $jsonReader.Close()
  26.       $mStream.Dispose()
  27.    }
  28. }
  29. }
  30.  
  31. function Convert-XmlToJson
  32. {
  33. PARAM([Parameter(ValueFromPipeline=$true)][xml]$xml)
  34. Process{
  35.    $mStream = new-object System.IO.MemoryStream
  36.    $jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream)
  37.    try
  38.    {
  39.      $xml.Save($jsonWriter)
  40.      $bytes = $mStream.ToArray()
  41.      [System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
  42.    }
  43.    finally
  44.    {
  45.      $jsonWriter.Close()
  46.      $mStream.Dispose()
  47.    }
  48. }
  49. }
  50.  
  51.  
  52.  
  53. function ConvertFrom-Json {
  54. PARAM( [Parameter(Mandatory=$true)][Type[]]$type, [Parameter(ValueFromPipeline=$true,Mandatory=$true)][String]$json )
  55. PROCESS{
  56.    $ms = New-object IO.MemoryStream (,$utf8.GetBytes($json))
  57.    Import-Json $type $ms
  58.    $ms.dispose()
  59. }
  60. }
  61.  
  62. function Import-Json {
  63. [CmdletBinding(DefaultParameterSetName="File")]
  64. PARAM(
  65. [Parameter(Mandatory=$true,Position=1)][Type[]]$type
  66. ,
  67. [Parameter(Mandatory=$true,Position=2,ParameterSetName="Stream")][IO.Stream]$Stream
  68. ,
  69. [Parameter(Mandatory=$true,Position=2,ParameterSetName="File")][String]$Path
  70. )
  71. BEGIN {
  72.    if($PSCmdlet.ParameterSetName -eq "File") {
  73.       $Stream = [IO.File]::Open($Path, "Read")
  74.    }
  75. }
  76. PROCESS{
  77.    if($type.Count -gt 1) {
  78.       $t,$types = @($type)
  79.       $js = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $t, (,@($types))
  80.    } else {
  81.       $js = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer @($type)[0]
  82.    }
  83.    Write-Output $js.ReadObject($Stream)
  84. }
  85. END {
  86.    if($PSCmdlet.ParameterSetName -eq "File") {
  87.       $Stream.Dispose()
  88.    }
  89. }
  90. }
  91.  
  92. function Export-Json {
  93. [CmdletBinding(DefaultParameterSetName="File")]
  94. PARAM(
  95. [Parameter(Mandatory=$true,Position=1)][Array]$InputObject
  96. ,
  97. [Parameter(Mandatory=$true,Position=2,ParameterSetName="Stream")][IO.Stream]$Stream
  98. ,
  99. [Parameter(Mandatory=$true,Position=2,ParameterSetName="File")][String]$Path
  100. )
  101. BEGIN {
  102.    if($PSCmdlet.ParameterSetName -eq "File") {
  103.       $Stream = [IO.File]::Open($Path, "Write")
  104.    }
  105. }
  106. PROCESS {
  107.    [type]$Type = @($InputObject)[0].GetType()
  108.  
  109.    if($Type -isnot [Array]) { #$InputObject.Count -gt 1 -and
  110.       [type]$Type = "$($Type)[]"
  111.    }
  112.    
  113.    [Type[]]$types = ($InputObject | select -expand PsTypeNames) | % { $_ -split "`n" -replace "^Selected\." } | Select -unique
  114.    
  115.    #Write-Verbose $($Types | select -expand FullName | out-string)
  116.    #Write-Verbose "Stream: $($Stream.GetType())"
  117.    Write-Verbose "Output: $Type"
  118.    Write-Verbose "Input: $($InputObject.GetType())"
  119.    
  120.    $js = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $Type #, $Types #, ([int]::MaxValue), $false, $null, $false
  121.    $js.WriteObject( $stream, $InputObject )
  122. }
  123. END {
  124.    if($PSCmdlet.ParameterSetName -eq "File") {
  125.       $Stream.Dispose()
  126.    }
  127. }
  128. }
  129.  
  130.  
  131. function ConvertTo-Json {
  132. PARAM( [Parameter(ValueFromPipeline=$true,Mandatory=$true)]$object )
  133. BEGIN {    
  134.    [type]$lastType = $null
  135.    function Out-JsonString {
  136.       Param($items)
  137.       $ms = New-Object IO.MemoryStream
  138.       Export-Json $items.ToArray() $ms
  139.       $utf8.GetString( $ms.ToArray(), 0, $ms.Length )
  140.       $ms.Dispose()
  141.    }
  142. }
  143. PROCESS {
  144.    $thisType = $object.GetType()
  145.    if(!$lastType -or $lastType -ne $thisType) {
  146.       if($lastType) { Out-JsonString $items }
  147.       # make a new collection
  148.       $items = new-object "System.Collections.Generic.List[$thisType]"
  149.    }
  150.    $items.Add($object)
  151.    $lastType = $thisType
  152. }
  153. END {
  154.    Out-JsonString $items
  155. }
  156. }
  157.  
  158. function Write-String {
  159. param([Parameter()]$stream,[Parameter(ValueFromPipeline=$true)]$string)
  160. process {
  161.   $bytes = $utf8.GetBytes($string)
  162.   $stream.Write( $bytes, 0, $bytes.Length )
  163. }  
  164. }
  165. New-Alias fromjson ConvertFrom-Json
  166. New-Alias tojson ConvertTo-Json
  167.  
  168. New-Alias cvfjs ConvertFrom-Json
  169. New-Alias cvtjs ConvertTo-Json
  170. New-Alias ipjs Import-Json
  171. New-Alias epjs Export-Json
  172.  
  173.  
  174. Export-ModuleMember -Function ConvertFrom-Json, Import-Json, Export-Json, ConvertTo-Json, Convert-JsonToXml, Convert-XmlToJson -Alias *

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me