Yesterday a friend of mine told me that he had a problem trying to make iceweasel restore bookmarks from ~/.mozilla/firefox/xxxxxxxx.default/bookmarkbackups/bookmarks-YYYY-MM-DD.json file. I suggested writing simple JSON => XML converter script in either Perl or Python.
I did look into my own bookmarks-2009-05-14.json file and discovered that it contains one line with ASCII representation of very long dict/list structure, similar to Python's str() output. First, I tried the most straighforward way:
>>> s = file("/tmp/bookmarks-2009-05-14.json", "r").readline()
>>> eval("x = %s" % s)
Traceback (most recent call last):
File "", line 1, in
File "", line 1
x = {"title":"","id":1,"dateAdded":1234807466297438,"lastModified":124112686
5065336,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"ti
tle":"Bookmarks Menu","id":2,"parent":1,"dateAdded":1234807466297884,"lastModifi
...
der=UNFILED_BOOKMARKS&expandQueries=0"}]}]}]}
^
SyntaxError: invalid syntax
>>> After that failure, I deciced to write full-fledged parser and even tried to find a decent Python parser generator. For this, I tried yapps2 first, but didn't like it and was forced to look for something better.
Next thing I tried was standard parser module. Surprisingly, it worked OK with the JSON after I declared JSON's null literal as eponymous variable in Python with value None, and replaced parser.expr() with parser.suite() (former is for expressins like a + 1 while latter accepts statements, e.g. x = a + 1):
>>> s = file("/tmp/bookmarks-2009-05-14.json", "r").readline()
>>> import parser
>>> ast = parser.suite("x = %s" % s)
>>> cod = ast.compile("foo.py")
>>> null = None
>>> eval(cod)
>>> from pprint import pprint
>>> pprint(x)
...
'lastModified': 1241126865065336L,
'root': 'placesRoot',
'title': '',
'type': 'text/x-moz-place-container'}
>>> Next thing to do is to generate XML. Probably, I'll do this tomorrow. --to be continued-- |