Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×
Programming

Journal morgan_greywolf's Journal: Never write another configuration parser -- ever. 1

Okay, so I'm a little slow at jumping on bandwagons. Having written code to parse everything from XML configuration files to Windows-style .INI files, I've always thought that writing code to create and parse configuration files sucked. And that things like ConfigParser and xml.dom.minidom in Python made it suck a little less.

So, having worked with XML, I had heard of JSON as an alternative to XML and always thought "Wow. I'm going to have to write ANOTHER parser? Ugh." Obviously I just didn't get it.

So I wrote a little proggie the other day and needed an object-oriented-type configuration file for it and thought, for some strange reason, they I should do something a little lighter weight than XML. Flat .INIs weren't going to work because, well, they're flat. ;) So I decided to give this JSON thing a try.

I looked at the JSON documentation for Python 2.6 (and simplejson for Python 2.5, which the Python 2.6 json module is based on) and went huh? That's it? That can't be it. I'll need to write more methods than that surely.

As I looked more and more at it, I realized uhhhh...a JSON file looks rather like a Python dictionary (like a hash table in Perl or C) with str and numeric values. And lists! (Values can be lists!) Perfect. And when you parse it, you get exactly that -- a big Python dictionary. Wow! *slaps forehead* How much easier can you make it than that?

So you can have


{
        "window": {
                "width": 150,
                "height": 200
        },
        "bookmarks": [
              {
                  "name": "Slashdot - News for Nerds. Stuff that Matters",
                  "url": "http://slashdot.org" },
              { "name": "Google Docs",
                  "url": "http://docs.google.com" },
        ]
}

(forgive me if Slashdot mangles the indentation as it usually does)

and then you can access the whole shebang via


>>> import json
>>> configFile=open('foo.rc','r')
>>> config=json.load(f)
>>> config['window']['height']
200
>>> for bookmark in config['bookmars']: print bookmark['url'] ...
http://slashdot.org
http://docs.google.com

And the JSON file can be entirely self-documenting: You can put literally anything you want for each of the key:value pairs.

And since writing out the JSON file is just easy (just in reverse), you can easily write a configuration GUI, with the same brand of direct access to the JSON structure.

Now that's easy.

This discussion has been archived. No new comments can be posted.

Never write another configuration parser -- ever.

Comments Filter:

"May your future be limited only by your dreams." -- Christa McAuliffe

Working...