json_helper.py
Go to the documentation of this file.
1 # Copyright 2017 Mycroft AI Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 import json
16 
17 
18 def merge_dict(base, delta):
19  """
20  Recursively merging configuration dictionaries.
21 
22  Args:
23  base: Target for merge
24  delta: Dictionary to merge into base
25  """
26 
27  for k, dv in delta.items():
28  bv = base.get(k)
29  if isinstance(dv, dict) and isinstance(bv, dict):
30  merge_dict(bv, dv)
31  else:
32  base[k] = dv
33 
34 
35 def load_commented_json(filename):
36  """ Loads an JSON file, ignoring comments
37 
38  Supports a trivial extension to the JSON file format. Allow comments
39  to be embedded within the JSON, requiring that a comment be on an
40  independent line starting with '//' or '#'.
41 
42  NOTE: A file created with these style comments will break strict JSON
43  parsers. This is similar to but lighter-weight than "human json"
44  proposed at https://hjson.org
45 
46  Args:
47  filename (str): path to the commented JSON file
48 
49  Returns:
50  obj: decoded Python object
51  """
52  with open(filename) as f:
53  contents = f.read()
54 
55  return json.loads(uncomment_json(contents))
56 
57 
58 def uncomment_json(commented_json_str):
59  """ Removes comments from a JSON string.
60 
61  Supporting a trivial extension to the JSON format. Allow comments
62  to be embedded within the JSON, requiring that a comment be on an
63  independent line starting with '//' or '#'.
64 
65  Example...
66  {
67  // comment
68  'name' : 'value'
69  }
70 
71  Args:
72  commented_json_str (str): a JSON string
73 
74  Returns:
75  str: uncommented, legal JSON
76  """
77  lines = commented_json_str.splitlines()
78  # remove all comment lines, starting with // or #
79  nocomment = []
80  for line in lines:
81  stripped = line.lstrip()
82  if stripped.startswith("//") or stripped.startswith("#"):
83  continue
84  nocomment.append(line)
85 
86  return " ".join(nocomment)
def uncomment_json(commented_json_str)
Definition: json_helper.py:58
def load_commented_json(filename)
Definition: json_helper.py:35
def merge_dict(base, delta)
Definition: json_helper.py:18


mycroft_ros
Author(s):
autogenerated on Mon Apr 26 2021 02:35:40