I am creating a JSON in Powershell and I want to set a custom tab width when building it (instead of the default 4 white spaces I want to set only 2 white spaces).
I am doing this because:
Sample code:
$object = New-Object PSObject
Add-Member -InputObject $object -MemberType NoteProperty -Name Phone -Value "SomePhone"
Add-Member -InputObject $object -MemberType NoteProperty -Name Description -Value "Lorem ipsum dolor.."
Add-Member -InputObject $object -MemberType NoteProperty -Name Price -Value 99.99
$object | ConvertTo-Json
Result with tab width = 4 white space characters.
{
"Phone": "SomePhone",
"Description": "Lorem ipsum dolor..",
"Price": 99.99
}
I tried compression but it doesn't give control over compression level (how agressive compression should be)
$object | ConvertTo-Json -Compress
Result compressed, obviously.
{"Phone":"SomePhone","Description":"Lorem ipsum dolor..","Price":99.99}
What I am trying to achieve: result with tab width = 2 white space characters.
{
"Phone": "SomePhone",
"Description": "Lorem ipsum dolor..",
"Price": 99.99
}
What I've tried so far is in the pseudo code below. I'm still in the loop. Please get me out of there :)
while (1) {
Google, StackOverflow
Try Stuff found
Tweak stuff found
if (Correct answer) {
break
}
}
The following code will halve the size of indent:
$json = @"
{
"Phone": "SomePhone",
"Description": "Lorem ipsum dolor..",
"Price": 99.99
}
"@
($json -split '\r\n' |
% {
$line = $_
if ($_ -match '^ +') {
$len = $Matches[0].Length / 2
$line = ' ' * $len + $line.TrimStart()
}
$line
}) -join "`r`n"