1# Copyright (c) 2012 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import json
6import os
7import sys
8
9_FILE_PATH = os.path.dirname(os.path.realpath(__file__))
10_SYS_PATH = sys.path[:]
11try:
12  _COMMENT_EATER_PATH = os.path.join(
13      _FILE_PATH, os.pardir, 'json_comment_eater')
14  sys.path.insert(0, _COMMENT_EATER_PATH)
15  import json_comment_eater
16finally:
17  sys.path = _SYS_PATH
18
19try:
20  from collections import OrderedDict
21
22  # Successfully imported, so we're running Python >= 2.7, and json.loads
23  # supports object_pairs_hook.
24  def Parse(json_str):
25    return json.loads(json_comment_eater.Nom(json_str),
26                      object_pairs_hook=OrderedDict)
27
28except ImportError:
29  # Failed to import, so we're running Python < 2.7, and json.loads doesn't
30  # support object_pairs_hook. simplejson however does, but it's slow.
31  #
32  # TODO(cduvall/kalman): Refuse to start the docs server in this case, but
33  # let json-schema-compiler do its thing.
34  #logging.warning('Using simplejson to parse, this might be slow! Upgrade to '
35  #                'Python 2.7.')
36
37  _SYS_PATH = sys.path[:]
38  try:
39    _SIMPLE_JSON_PATH = os.path.join(_FILE_PATH,
40                                     os.pardir,
41                                     os.pardir,
42                                     'third_party')
43    sys.path.insert(0, _SIMPLE_JSON_PATH)
44    # Add this path in case this is being used in the docs server.
45    sys.path.insert(0, os.path.join(_FILE_PATH,
46                                    os.pardir,
47                                    os.pardir,
48                                    'third_party',
49                                    'json_schema_compiler'))
50    import simplejson
51    from simplejson import OrderedDict
52  finally:
53    sys.path = _SYS_PATH
54
55  def Parse(json_str):
56    return simplejson.loads(json_comment_eater.Nom(json_str),
57                            object_pairs_hook=OrderedDict)
58
59
60def IsDict(item):
61  return isinstance(item, (dict, OrderedDict))
62