73 lines
2.2 KiB
Python
73 lines
2.2 KiB
Python
|
# Copyright (c) 2017 Mycroft AI, Inc.
|
||
|
#
|
||
|
# This file is part of Mycroft Core.
|
||
|
#
|
||
|
# Mycroft Core is free software: you can redistribute it and/or modify
|
||
|
# it under the terms of the GNU General Public License as published by
|
||
|
# the Free Software Foundation, either version 3 of the License, or
|
||
|
# (at your option) any later version.
|
||
|
#
|
||
|
# Mycroft Core is distributed in the hope that it will be useful,
|
||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
|
# GNU General Public License for more details.
|
||
|
#
|
||
|
# You should have received a copy of the GNU General Public License
|
||
|
# along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>.
|
||
|
|
||
|
|
||
|
import json
|
||
|
|
||
|
def load_commented_json(filename):
|
||
|
""" Loads an JSON file, ignoring comments
|
||
|
|
||
|
Supports a trivial extension to the JSON file format. Allow comments
|
||
|
to be embedded within the JSON, requiring that a comment be on an
|
||
|
independent line starting with '//' or '#'.
|
||
|
|
||
|
NOTE: A file created with these style comments will break strict JSON
|
||
|
parsers. This is similar to but lighter-weight than "human json"
|
||
|
proposed at https://hjson.org
|
||
|
|
||
|
Args:
|
||
|
filename (str): path to the commented JSON file
|
||
|
|
||
|
Returns:
|
||
|
obj: decoded Python object
|
||
|
"""
|
||
|
with open(filename) as f:
|
||
|
contents = f.read()
|
||
|
|
||
|
return json.loads(uncomment_json(contents))
|
||
|
|
||
|
|
||
|
def uncomment_json(commented_json_str):
|
||
|
""" Removes comments from a JSON string.
|
||
|
|
||
|
Supporting a trivial extension to the JSON format. Allow comments
|
||
|
to be embedded within the JSON, requiring that a comment be on an
|
||
|
independent line starting with '//' or '#'.
|
||
|
|
||
|
Example...
|
||
|
{
|
||
|
// comment
|
||
|
'name' : 'value'
|
||
|
}
|
||
|
|
||
|
Args:
|
||
|
commented_json_str (str): a JSON string
|
||
|
|
||
|
Returns:
|
||
|
str: uncommented, legal JSON
|
||
|
"""
|
||
|
lines = commented_json_str.splitlines()
|
||
|
# remove all comment lines, starting with // or #
|
||
|
nocomment = []
|
||
|
for line in lines:
|
||
|
stripped = line.lstrip()
|
||
|
if stripped.startswith("//") or stripped.startswith("#"):
|
||
|
continue
|
||
|
nocomment.append(line)
|
||
|
|
||
|
return " ".join(nocomment)
|