Working with unindented XML and JSON data can be a real PITA. Searching the net for a handy plugin for my text editor, I came across this pretty neat article.
Source: http://www.connorgarvey.com/blog/?p=264
Here’s how to add commands to Gedit to format JSON and XML documents.
- Ensure that you have an up-to-date version of Python. It’s included with nearly every Linux distribution.
- Ensure that the External Tools plugin is installed
- Click Edit -> Preferences
- Select the Plugins tab
- Check the box next to External Tools
- Click Close
- Add the Format JSON command
- Click Tools -> Manage External Tools…
- Click New (bottom left, looks like a piece of paper with a plus sign)
- Enter a name (Format JSON)
- Paste this text into the text window on the right
#! /usr/bin/env python
import json
import sysj = json.load(sys.stdin)
print json.dumps(j, sort_keys=True, indent=2)
- Set Input to Current document
- Set Output to Replace current document
- Add the Format XML command
- Install lxml (on Ubuntu, sudo apt-get install python-lxml)
- Python’s included XML modules either don’t support pretty printing or are buggy
- Create a new external tool configuration as above (Format XML)
- Paste this text into the text window on the right
#! /usr/bin/env python
import sys
import lxml.etree as etree
import tracebackresult = ''
for line in sys.stdin:
result += line
try:
x = etree.fromstring(result)
result = etree.tostring(x, pretty_print=True, xml_declaration=True, encoding=”UTF-8″)
except:
etype, evalue, etraceback = sys.exc_info()
traceback.print_exception(etype, evalue, etraceback, file=sys.stderr)
print result
- Set Input to Current document
- Set Output to Replace current document