8

PowerShellでJSONを解析したいのですが、PowerShellで使用できる新しいv3関数を使用できません。私の最初の考えは、JSON.Netアセンブリをロードし、それを使用してJSON文字列を解析することでしたが、期待どおりに機能しません。

私はこのJSONを持っています:

$json = "{""Name"": ""Apple"",  
           ""Price"": 3.99,  
            ""Sizes"": [    
                 ""Small"",    
                 ""Medium"",
                 ""Large""]}"

次のコードを使用してJSON.NETアセンブリをロードします。

[Reflection.Assembly]::LoadFile("$currentPath\Newtonsoft.Json.dll”)

そしてそれを解析しようとします

$result = [Newtonsoft.Json.JsonConvert]::DeserializeObject($json)

今はそうなると思います$result["Name"]Apple、何も得られません。何か案は?

コード´$ result.ContainsKey( "Name")returnsTrue but$ result.GetValue( "Name")null` returns

4

3 に答える 3

13

さて、これが私がそれを行った方法であり、少なくともWindows2008のPowerShellv2まで機能します。

まず、使用したいバージョンのJson.NETアセンブリをロードし、.NET3.5バージョンを使用しました。

[Reflection.Assembly]::LoadFile("Newtonsoft.Json.dll")

作成したデプロイメント構成で使用されていたため、ファイルにJSONが含まれていたため、ファイルを読み取ってからjsonを解析する必要がありました。

$json = (Get-Content $FileName | Out-String) # read file
$config = [Newtonsoft.Json.Linq.JObject]::Parse($json) # parse string

Itemここで、構成から値を取得するには、ハッシュテーブル/ディクショナリでPowerShellによって定義されているように見えるメソッドを使用する必要があります。したがって、単純な文字列であるアイテムを取得するには、次のように記述します。

Write-Host $config.Item("SomeStringKeyInJson").ToString()

あなたがたくさんのことをしているなら、あなたは次のようなことをする必要があるでしょう

$config.Item("SomeKeyToAnArray") | ForEach-Object { Write-Host $_.Item("SomeKeyInArrayItem").ToString() }

あなたが書いたネストされたアイテムにアクセスするには

$config.Item("SomeItem").Item("NestedItem")

これが、PowerShellでJson.NETを使用したJSONの解析を解決した方法です。

于 2012-12-21T12:13:38.910 に答える
8

ここにアクセスしてPowershell5.0を使用している場合は、PowerShellギャラリーで入手できます。

Install-Module Newtonsoft.Json
Import-Module Newtonsoft.Json

$json = '{"test":1}'
[Newtonsoft.Json.Linq.JObject]::Parse($json)
于 2019-06-13T00:10:39.900 に答える
5

多分これはあなたが求めているものです:

http://poshcode.org/2930

    function Convert-JsonToXml {
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN { 
   $mStream = New-Object System.IO.MemoryStream 
}
PROCESS {
   $json | Write-Stream -Stream $mStream
}
END {
   $mStream.Position = 0
   try
   {
      $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
      $xml = New-Object Xml.XmlDocument
      $xml.Load($jsonReader)
      $xml
   }
   finally
   {
      $jsonReader.Close()
      $mStream.Dispose()
   }
}
}

function Write-Stream {
PARAM(
   [Parameter(Position=0)]$stream,
   [Parameter(ValueFromPipeline=$true)]$string
)
PROCESS {
  $bytes = $utf8.GetBytes($string)
  $stream.Write( $bytes, 0, $bytes.Length )
}  
}



$json = '{
    "Name": "Apple",
    "Expiry": 1230422400000,
    "Price": 3.99,
    "Sizes": [
        "Small",
        "Medium",
        "Large"
    ]
}'

Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8                 
(convert-jsonToXml $json).innerXML

出力:

<root type="object"><Name type="string">Apple</Name><Expiry type="number">1230422
400000</Expiry><Price type="number">3.99</Price><Sizes type="array"><item type="s
tring">Small</item><item type="string">Medium</item><item type="string">Large</it
em></Sizes></root>

名前ノードが必要な場合:

$j=(convert-jsonToXml $json)
$j.SelectNodes("/root/Name")

また

$j |Select-Xml -XPath "/root/Name" |select -ExpandProperty node
于 2012-12-20T08:39:35.263 に答える