Saturday, August 4, 2012

Gedit JSON, XML formatting plugin

Here’s how to add commands to Gedit to format JSON and XML documents.

  1. Ensure that you have an up-to-date version of Python.  It’s included with nearly every Linux distribution.
  2. Ensure that the External Tools plugin is installed
    1. Click Edit -> Preferences
    2. Select the Plugins tab
    3. Check the box next to External Tools
    4. Click Close
  3. Add the Format JSON command
    1. Click Tools -> Manage External Tools…
    2. Click New (bottom left, looks like a piece of paper with a plus sign)
    3. Enter a name (Format JSON)
    4. Paste this text into the text window on the right
 code :
         
#! /usr/bin/env python
 
import json
import sys
 
j = json.load(sys.stdin)
print json.dumps(j, sort_keys=True, indent=2)
 
  1. Set Input to Current document
  2. Set Output to Replace current document
  1. Add the Format XML command
    1. Install lxml (on Ubuntu, sudo apt-get install python-lxml)
      1. Python’s included XML modules either don’t support pretty printing or are buggy
    2. Create a new external tool configuration as above (Format XML)
    3. Paste this text into the text window on the right
#! /usr/bin/env python
 
import sys
import lxml.etree as etree
import traceback
 
result = ''
for line in sys.stdin:
  result += line
try:
  x = etree.fromstring(result)
  result = etree.tostring(x, pretty_print=True)
except:
  etype, evalue, etraceback = sys.exc_info()
  traceback.print_exception(etype, evalue, etraceback, file=sys.stderr)
print result

  1. Set Input to Current document
  2. Set Output to Replace current document

original score : www.connorgarvey.com/blog/?p=264

2 comments:

  1. Very helpful. Thanks.

    ReplyDelete
  2. For python3, just change 'print result' to 'print(result.decode("utf-8"))'

    ReplyDelete