14

Is there a way to minify (remove all whitespace in this case) a JSON file to turn this

[
    0.000005,
    0,
    0
],
[
    219.740502,
    0.003449,
    4.177065
],
[
    45.210918,
    0.003365,
    -16.008996
],
[
    344.552785,
    0.030213,
    277.614965
],

to this using PowerShell

[0.000005,0,0],[219.740502,0.003449,4.177065],[45.210918,0.003365,-16.008996],[344.552785,0.030213,277.614965],

I have tried several online "minifiers" however the file contains over 100,000 arrays and basically broke all the online minifiers. Any ideas?

3 Answers 3

32

Just for your information when you manipulate PowerShell object and convert them to JSON (ConvertTo-Json) you've got the -compress param :

New-Object -TypeName PSCustomObject -Property @{Name="Hugot";GivenName="Victor"} | ConvertTo-Json -Compress

gives :

{"GivenName":"Victor","Name":"Hugot"}
1
  • 2
    much better answer
    – 4c74356b41
    Feb 7, 2017 at 11:54
17

Adding to JP's answer,

(ConvertFrom-Json $json) | ConvertTo-Json -Compress

This is useful if you already have json. If you don't do the ConvertFrom-Json on the front, then it will encode the line breaks with \r\n and the quotes with \".

0

You can easily do so with a basic regex. If you have this in a file try the following. You must include the -Raw parameter or the file will be passed one line at a time which will prevent the regex from removing the newline character.

(Get-Content C:\Some\File.json -Raw) -replace '\s','' | out-file C:\some\outfile.json
2
  • 3
    Big warning here! This command will output the result in UTF-16. That's not really a problem unless you are trying to compute a hash on the content. Just make sure that the resulting encoding is what you expect. Even when using the -encoding switch, the output will give you UTF8 with BOM. That will mess with your hash computation of the file.
    – dayneo
    Apr 8, 2018 at 11:37
  • 8
    Won't this remove spaces from strings, which proper minification shouldn't do? Jun 30, 2019 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.