iferminm
iferminm

Reputation: 2059

How do I json-format and override multiple files?

I have several unformatted json files I would like to "prettify" so they're more human readable. The way I usually do it for a single file is:

python -m json.tool < infile > outfile

But for several files I haven't found a way to process them and override the same file with the new "pretty" json.

The closest I got was:

find ./ -type f -exec python -m json.tool {} \;

But it prints everything to standard output, which is fine but not optimal depending on how many files you're looking at. Is there any way to make the above command override the files with the prettified json?

Files are called: message1.json, message2.json and so on...

Thanks in advance

Upvotes: 0

Views: 1526

Answers (2)

Andrew Thaddeus Martin
Andrew Thaddeus Martin

Reputation: 3285

This is very similar to the already accepted answer, but it uses sponge (on debian, this is part of the moreutils package) to avoid creating an intermediate file in /tmp:

find . -type f -name '*.json' -exec sh -c 'python3 -m json.tool < $0 | sponge $0' {} \;

Upvotes: 0

pasaba por aqui
pasaba por aqui

Reputation: 3529

Try with:

find . -type f -exec sh -c 'python -m json.tool $0 > $0.pretty' {} \;

see at https://stackoverflow.com/a/12965441/4886927 for detailed explanation

In this way the original file is overwritten with new one:

find . -type f -exec sh -c 'python -m json.tool < $0 > /tmp/pretty.json && mv  /tmp/pretty.json $0' \;

Upvotes: 2

Related Questions