ezdazuzena
ezdazuzena

Reputation: 6770

JSON pretty format only of part of a file in vim

In VIm, is there a way to print a JSON snipped inside a file in the "pretty" format?

For example, having the following file

# a comment
def my_func():
    pass

{"bla": [1, 2, 3], "yes": false}  # <--- pretty print this

# another comment
<foo>why do I mix everything in one file?</foo>
<bar>it's an example, dude</bar>

I would like to change the marked line to

{
   "bla":[
      1,
      2,
      3
   ],
   "yes":false
}

I'm looking for something like :%!python -m json.tool but only for the selected lines.

Upvotes: 5

Views: 1129

Answers (2)

Alan G&#243;mez
Alan G&#243;mez

Reputation: 378

A regex-based solution is:

:%s/\({\)\|\(\[\)\|\(,\)\|\(\]\)\|\(}\)/\1\2\3\r\4\5/g

followed by: =gg

outputs:

{
   "bla": [
      1,
      2,
      3
   ],
   "yes": false
}

Upvotes: 0

Marc
Marc

Reputation: 163

Specifying the line number should work. For example:

:5!python -m json.tool

Or if it takes multiple lines:

:4,6!python -m json.tool

Upvotes: 12

Related Questions