Formatting multiple json files recursively
Asked Answered
M

3

9

This is a theoretical question about minimizing side effects in bash scripting.

I recently used a simple mechanism for formatting a bunch of json files, in a nested directory structure...

for f in `find ./ -name *json`; do echo $f ; python -mjson.tool $f > /tmp/1 && cp /tmp/1 $f ; done.   

The mechanism is simply to

  • format each file using python's mjson.tool,
  • write it to a tmp location, and
  • then rewrite it back in place.

Is there a way to do this which is more elegant, i.e. with minimal side effects? I'm assuming bash experts have a better way of doing this sort of thing .

Marelda answered 5/4, 2015 at 13:45 Comment(1)
i noticed a downvote. any particular reason? side effect free bash scripting seems like a valuable discussion item.Marelda
F
7

Unix tools working on a streaming basis -- they don't store all of the contents of the files in memory at once. Therefore, you have to use an intermediary location since you would be overwriting a file that is currently being read from.

You may consider that your snippet isn't fault tolerant. If you make a mistake, you would have just overwritten all your data. You should store the output in a new location, verify, then move to overwrite. :)

Firestone answered 5/4, 2015 at 15:10 Comment(0)
N
1

Using Eclipse IDE we can achieve formatting for multiple JSON files

Import the files into eclipse and select the files (you wish to format) or folder(for all the files) and right click -> source -> format

Numismatology answered 5/6, 2020 at 8:31 Comment(0)
H
0

I was looking for something similar and just noticed I can select all JSON files I have in my VSCode file panel and CTRL + Click > "Format". Works like magic for a one-off operation, it's formatting the files in-place.

VSCode format in action

Hackworth answered 6/7, 2020 at 12:1 Comment(1)
Please note that you need the Format in context menus extension for this menu item to be available. Another extension that works well to achieve batch formatting is Format Files which allows you to batch format all files in your workspace.Lacteal

© 2022 - 2025 — McMap. All rights reserved.