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
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
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.
probably not news (Score:1)
I saw this entry and yours about the same time
No idea if it is useful to you or you have already seen this stuff
http://blog.mozilla.com/webdev/2009/02/12/native-json-in-firefox-31/ [mozilla.com]
https://developer.mozilla.org/En/Using_JSON_in_Firefox [mozilla.org]