JavaChipMocha
JavaChipMocha

Reputation: 189

PowerShell to prettify multiple JSON files in one folder

My goal is to prettify all the JSON files (about 70K of them) in one folder. Say I have one folder named "juicero" and in there there are about 70K .JSON files with different names - a.json, b.json

This is what I tried -

PS> $files = Get-ChildItem C:\users\gamer\desktop\juicero\*.json
PS> $json_test = (Get-Content $files -raw | ConvertFrom-Json)
PS> foreach ($file in $files) { ConvertTo-Json | Set-Content $files }

I thought it would iterate through the path and prettify these (pretty straight-forward logic) but for some reason, this is deleting the content of the files. If I don't iterate and just use this function on one .json file it works - so I'm guessing there is something wrong with the iteration logic?

Upvotes: 1

Views: 650

Answers (1)

Robert Dyjas
Robert Dyjas

Reputation: 5227

You need to work on files inside the loop, like that:

foreach ($file in $files) {
  $content = Get-Content $file -Raw | ConvertFrom-Json
  $newFilePath = $file.FullName.Replace("OldFolder","NewFolder")
  ConvertTo-Json -InputObject $content| Set-Content $newFilePath
}

Notice that I'm putting output files into new folder, for easier debugging in case any issues.


There's one more issue with your code. Here you're converting all the files at once:

$json_test = (Get-Content $files -raw | ConvertFrom-Json)

However, later on, PowerShell has no information about source file name (file name is not included in $json_test).

Upvotes: 1

Related Questions