How to indent JSON data inside of TextMate, Emacs, BBEdit, or Sublime Text 2?
Solution 1: Using Python
This answer is similar to this answer, except I am using python file
to do the JSON format.
- Exit
bbedit
application if it is open, - put following script pretty-json.py in
~/Library/Application\ Support/BBEdit/Text\ Filters/
path
#!/usr/bin/env python
# You can change above she-bang line depending on your Mac configuration
import sys
import json
def main():
input = sys.stdin.read()
try:
obj = json.loads(input)
except Exception as e:
print input + "\n\nERROR: " + str(e)
return 1
print(json.dumps(obj, indent=2))
return 0
if __name__ == '__main__':
sys.exit(main())
To Test, open a JSON file in BBEdit.
Select
Text
-->Apply Text Filter
-->pretty-json.py
If you face any issue like formatting error, then the above script will add error in New file and will not change the original JSON.
which is not the case with this answer
Ref: https://gist.github.com/brokaw/95ade1358954cd97d0f2c8e992e14b08
For more info: Refer this
The above filter works fine for smaller JSON files, but if the JSON file is large(~ 40MB) then formatting will be slow.
To solve this, use the following solution
Solution 2: Using jq
For faster json formatting,
- Install jq
brew install jq
- Check if you are able to execute
jq
in terminal, or need a full path, add whichever works in following file in place ofjq
- Add
fast-json-pretty.sh
file in~/Library/Application\ Support/BBEdit/Text\ Filters/
location - Restart bbedit.
#!/bin/bash
jq
I found a solution for BBEdit that is easy and works well.
Put the following script in~/Library/Containers/BBEdit/Data/Library/Application Support/BBEdit/Text Filters/FormatJSON.sh
(on MacOS 11 Big Sur, or above)
For MacOS 10.15 Catalina and below, use this location: ~/Library/Application Support/BBEdit/Text Filters/FormatJSON.sh
#!/bin/bash
python -m json.tool
- Open a JSON file in BBEdit. There is no need to restart BBEdit because BBEdit rocks!
- Select Text > Apply Text Filter > FormatJSON
I tested this with a JSON file that had 3,612,683 characters on a single line. BBEdit opened this file and reformatted without showing a "Spinning Beachball of Death" busy-wait mouse cursor.