web-dev-qa-db-ja.com

PowerShell 3でJSONを美しくする

標準のjson文字列値が与えられた場合:

$jsonString = '{ "baz": "quuz", "cow": [ "moo", "cud" ], "foo": "bar" }'

どうすればこれを改行できれいにできますか?

これまでに見つけた最も簡単な方法は次のとおりです。

$jsonString | ConvertFrom-Json | ConvertTo-Json 

しかし、それはちょっとばかげているようです。

26
Eris

私のために働く。括弧は、パイプの前にget-contentが行われることを確認します。 convertto-jsonのデフォルトの深さは2で、多くの場合低すぎます。

function pjson ($jsonfile) {
  (get-content $jsonfile) | convertfrom-json | convertto-json -depth 100 | 
    set-content $jsonfile
}
11
js2010

組み込みのPowerShell関数| ConvertFrom-Json | ConvertTo-Jsonを使用するという最も単純な方法を本当に使いたくない場合は、JSON.netを使用する別の方法を次に示します

# http://james.newtonking.com/projects/json-net.aspx
Add-Type -Path "DRIVE:\path\to\Newtonsoft.Json.dll"

$jsonString = '{ "baz": "quuz", "cow": [ "moo", "cud" ], "foo": "bar" }'
[Newtonsoft.Json.Linq.JObject]::Parse($jsonString).ToString()
4
TechSpud