Source code for inspec.tools

# -*- coding: utf-8 -*-
# Time-stamp: <2021-03-16 17:03:31 ycopin>

"""
.. _tools:

tools - Miscellaneous tools
===========================
"""




[docs]def parse_json(filename): """ Parse a JSON file (filtering comments on the fly) into an `OrderedDict`. *Unofficial* JSON comments look like:: // ... or:: /* ... */ Source: `D. Riquet <http://www.lifl.fr/~damien.riquet/parse-a-json-file-with-comments.html>`_ """ import json import re from collections import OrderedDict # Regular expression for comments comment_re = re.compile(r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?', re.DOTALL | re.MULTILINE) 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) # Return OrderedDict from parsed JSON file content return json.loads(content, object_pairs_hook=OrderedDict)