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

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(

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

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

        print content

        # Return json file
        return json.loads(content)

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

Comments !