vrijdag 24 mei 2013

JSON & XML formatting in Gedit

With some simple configuration and python scripting gedit is able to format JSON and XML documents.

Open gedit and select Manage external tools from the tools menu.
Create a new tool configuration by clicking the + sign.

Provide a sensible name (Format JSON) and insert the following python script:

#! /usr/bin/env python
import json
import sys

j = json.load(sys.stdin)
print json.dumps(j, sort_keys=True, indent=2)


The result should be something like this:




The steps for XML are the same as long as you choose another name for the tool configuration.
Here's the script for XML formatting:

#! /usr/bin/env python

import sys
import lxml.etree as etree
import traceback

result = ''
for line in sys.stdin:
  result += line.strip()
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



Now paste some unformatted XML or JSON text in a new document and apply your new tools from the tool menu.

Note: I did not created these scripts. I just found and shared them :)