Prettify json in powershell 3

Eris picture Eris · Jul 16, 2014 · Viewed 23.1k times · Source

Given a standard json string value:

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

How can I get this to be all pretty with newlines, preferably without brute-force regex?

Simplest method I've found so far is:

$jsonString | ConvertFrom-Json | ConvertTo-Json 

However, that seems kinda silly.

Answer

js2010 picture js2010 · Jun 16, 2017

Works for me. Parentheses make sure get-content is done before piping. Default depth of convertto-json is 2, which is often too low.

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