Parse a JSON file with comments

I like to use JSON files with python. It's very simple to read and use such files. For example:

JSON file

{
    "username": "John Smith",
    "age": 42,
    "list": ["a", "b", "c"]
}

Python script

import json

with open('file.json') as f:
    d = json.load(f)
    print d['username']
    print d['age']
    print ','.join(d['list'])

will print:

John Smith
42
a,b,c

I usually use JSON files to configure scripts. And such files could become easily unreadable. That's why I wanted to include some comments, but unfortunately JSON files cannot contain comments.

So I wrote a short piece of Python code that wraps the JSON parser:

import json
import re

# Regular expression for comments
comment_re = re.compile(
    '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
    re.DOTALL | re.MULTILINE
)

def parse_json(filename):
    """ Parse a JSON file
        First remove comments and then use the json module package
        Comments look like :
            // ...
        or
            /*
            ...
            */
    """
    with open(filename) as f:
        content = ''.join(f.readlines())

        ## Looking for comments
        match = comment_re.search(content)
        while match:
            # single line comment
            content = content[:match.start()] + content[match.end():]
            match = comment_re.search(content)


        print content

        # Return json file
        return json.loads(content)

Feel free to use this code. Beerware / WTFPL licence.

Comments !