How to indent JSON data inside of TextMate, Emacs, BBEdit, or Sublime Text 2?
Asked Answered
P

10

17

[Update: 8 hours after this question was posted, the author of JSON bundle was notified of the issue and he fixed it.]

I have the following JSON data in a file application.json, shown at the end of this post, and I have used TextMate with the JSON bundle, Emacs, BBEdit, and Sublime Text 2 to properly indent it, but all seemed like they couldn't.

Both TextMate and Sublime Text 2 insisted that the first { should not be indented, and the first major issue was for the closing brace for "child": {. Both TextMate and Sublime Text 2 refused to align the } under the left side of "child": {. Emacs kept on indenting further and further for each line, and BBEdit didn't seem to have an re-indent function at all (could this be?).

Is there a way to properly indent the file, or are TextMate and Sublime Text 2 both doing the right thing for the JSON data?

[ 
{
    "settings": [ "master" ],
    "appPort": "8666",
    "specs": {
        "frame" : {
            "type" : "HTMLFrameMojit",

            "config": {
                "deploy": true,
                "child": {
                    "type" : "HelloWorldMojit"
                    },
                    "assets": {
                        "top": {
                            "css": [
                            "/static/HelloWorldMojit/assets/index.css"
                            ]
                        }
                    }
                }
            }
        }
        },
        {
            "settings": [ "environment:development" ],
            "staticHandling": {
                "forceUpdate": true
            }
        }
        ]
Peacetime answered 12/1, 2013 at 2:17 Comment(0)
G
4

I just corrected this issue in the bundle, for 2.0 users the bundle should update within 24 hours with the correction.

Gladiatorial answered 12/1, 2013 at 10:48 Comment(0)
H
42

EDIT: For BBEdit use siegel's suggestion of Text > Reformat Document

Original Reply:

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
  1. Open a JSON file in BBEdit. There is no need to restart BBEdit because BBEdit rocks!
  2. 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.

Haggadah answered 17/10, 2013 at 14:26 Comment(7)
There should be another / between Text Filters and FormatJSON.Multilingual
AppCode has built in support for JSON and should reformat it, but I haven't tried it, and it is not inexpensive.Haggadah
Note that this may reorder the file, not merely reindent it.Bobsleigh
The folder location listed for Catalina and below is in fact the correct location for above too, certainly Mac OS 12 (Monterey)Didier
The folder location on MacOS 12 Monterey is ~/Library/Application Support/BBEdit/Text Filters.Umbrella
You might need python3 -m json.tool, depending on how you installed Python.Juliannajulianne
I'm on macOS Ventura. @SteveU suggested location of ~/Library/Application Support/BBEdit/Text Filters/FormatJSON.sh containing @Juliannajulianne suggested python3 -m json.tool works on my Mac.Enrage
A
11

In BBEdit 14.0 and later, "Reformat Document" on the text menu will reflow JSON. You can also use the built-in Language Server Support with a JSON language server that supports reformatting.

Altercation answered 17/3, 2022 at 14:20 Comment(1)
the feature workable!Elysia
P
6

Solution 1: Using Python

This answer is similar to this answer, except I am using python file to do the JSON format.

  1. Exit bbedit application if it is open,
  2. 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())
  1. To Test, open a JSON file in BBEdit.

  2. Select Text --> Apply Text Filter --> pretty-json.py

  3. 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,

  1. Install jq brew install jq
  2. Check if you are able to execute jq in terminal, or need a full path, add whichever works in following file in place of jq
  3. Add fast-json-pretty.sh file in ~/Library/Application\ Support/BBEdit/Text\ Filters/ location
  4. Restart bbedit.
#!/bin/bash
jq
Pipit answered 8/2, 2019 at 8:23 Comment(2)
Solution 2 totally rocks and you do not need to quit / restart BBEdit. In fact you can use BBEdit to create and save the shell script and then you can use it, immediately, on a json file that was already open.Authorship
All credit goes to the contributors of jq library.Pipit
G
4

I just corrected this issue in the bundle, for 2.0 users the bundle should update within 24 hours with the correction.

Gladiatorial answered 12/1, 2013 at 10:48 Comment(0)
P
2

According to http://jsonprettyprint.com/ Textmate and Sublime aren't doing the right thing.

What version of Emacs did you use?

With 24.2.1, your JSON blob indented perfectly without issues in js-mode (Emac's default javascript major-mode).


If you do any significant Javascript development I recommend checkint out js2-mode https://github.com/mooz/js2-mode, which turns Emacs into a great JS IDE.

Peak answered 12/1, 2013 at 3:39 Comment(1)
I tried the newest Emacs on Fedora (Emacs 24.1.1) and it worked perfectly, so the question is, how can Emacs on the Mac be upgraded? (update: my Emacs is 22.1.1 on OS X Lion, and following the instruction for js2-mode on GitHub, it won't add the js2-mode to Emcas)Peacetime
M
0

Sublime Pretty JSON

Sublime Pretty JSON indents the first { well. This is what I get:

[
  {
    "settings": [
      "master"
    ],
    "appPort": "8666",
    "specs": {
      "frame": {
        "type": "HTMLFrameMojit",
        "config": {
          "deploy": true,
          "child": {
            "type": "HelloWorldMojit"
          },
          "assets": {
            "top": {
              "css": [
                "/static/HelloWorldMojit/assets/index.css"
              ]
            }
          }
        }
      }
    }
  },
  {
    "settings": [
      "environment:development"
    ],
    "staticHandling": {
      "forceUpdate": true
    }
  }
]

Installation

Within Sublime Text 2: Preference => Package Control => Install Package => "Pretty Json" => Restart Sublime => Select JSON Text => Press:

  • Linux: ctrl+alt+j
  • Windows: ctrl+alt+j
  • OS X: cmd+ctrl+j
Marr answered 22/4, 2015 at 7:23 Comment(0)
P
0

This is a solution simply using Google Chrome or NodeJS itself, and here is how:

Just open up the Google Chrome dev tool or NodeJS prompt, and type in

obj = 

and copy and paste the object into it, so it will be like

obj = [
      { 
        // etc

Now, in Google Chrome, just type

JSON.stringify(obj, null, 4)

and you will have the formatted JSON. In NodeJS, since it prints out the \n verbatim, you can use

console.log(JSON.stringify(obj, null, 4))

If you want the indentation to be just 2 spaces, just use 2 instead of 4.

If you want the indentation to be tabs instead of spaces, simply use

JSON.stringify(obj, null, "\t")
Peacetime answered 27/12, 2020 at 11:43 Comment(0)
C
0
  1. Create a script file fast-json-pretty.sh in ~/Library/Application\ Support/BBEdit/Text\ Filters/
  2. Insert the following script:
#!/usr/bin/env bash
/usr/local/bin/jq .
  1. Apply the text filter as follows: Menu bar --> Text --> Apply Text Filter --> fast-json-pretty

This is a reworked version of DKB's version of his JQ script as it, at least for me, required the full path and a dot (.) at the end to make this work.

Customs answered 30/6, 2021 at 7:5 Comment(0)
S
0

Just check to see which version of python is installed:

using json_pretty will only work if the python interpreter is whatever is installed in the shell being called. For example, my json_pretty works and I have modded it as follows on Ventura:

#!/bin/zsh
python3 -m json.tool
Shaduf answered 5/12, 2022 at 21:55 Comment(0)
Q
0

To summarise what worked in the MacOS Sonoma with BBEdit 14, I will list the steps I gathered from inputs from many of you below, in order to make an effective JSON formatting functionality for the BBEdit tool that is based on Python's json.dumps(..) functionality:

Step 1. Download and save the https://raw.githubusercontent.com/dineshbhagat/mac-configurations/main/bbedit/pretty-json.py as ~/Library/Application Support/BBEdit/Text Filters/json.tool in your Mac. In case URL didn't work, the content of this file is as follows:

#!/usr/bin/env python

# You can change above she-bang line depends on Mac
# A text filter for BBEdit that doesn't clobber your original file in the case of an error.
# I was annoyed by text filters that destroy the active text buffer on a parse error.
# This version will echo out the original text and append an error message.
# c.f. http://crisp.tumblr.com/post/2574967567/json-pretty-print-formatting-in-bbedit
# c.f. http://blog.scottlowe.org/2013/11/11/making-json-output-more-readable-with-bbedit/

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())

Step 2. Create the shell file to run the python (because python new interpreter is called python3). Create a file at ~/Library/Application Support/BBEdit/Text Filters/fast-json-pretty.sh and add the below content:

#!/bin/zsh
python3 -m json.tool

Step 3. Now the BBEdit would have done the magic (no need to even restart!). Click the menu item Text > Apply Text Filter > fast-json-pretty and the file should be formatted. Here's a screenshot:

BBEdit new menu for JSON formatting

NOTE: One thing to note is that extra json menu-option coming up is because of the json.tool file that has the python code. I decided to ignore that. Nice thing I noticed is that the changes this new script do to your text file can be undone by the usual CMD+Z!

Enjoy!

Quickly answered 30/5 at 12:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.