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 copy 6 7import json_parse 8 9def DeleteNodes(item, delete_key): 10 """Deletes the given nodes in item, recursively, that have |delete_key| as 11 an attribute. 12 """ 13 def HasKey(thing): 14 return json_parse.IsDict(thing) and thing.get(delete_key, False) 15 16 if json_parse.IsDict(item): 17 toDelete = [] 18 for key, value in item.items(): 19 if HasKey(value): 20 toDelete.append(key) 21 else: 22 DeleteNodes(value, delete_key) 23 for key in toDelete: 24 del item[key] 25 elif type(item) == list: 26 item[:] = [DeleteNodes(thing, delete_key) 27 for thing in item if not HasKey(thing)] 28 29 return item 30 31 32def Load(filename): 33 with open(filename, 'r') as handle: 34 schemas = json_parse.Parse(handle.read()) 35 return schemas 36 37 38# A dictionary mapping |filename| to the object resulting from loading the JSON 39# at |filename|. 40_cache = {} 41 42 43def CachedLoad(filename): 44 """Equivalent to Load(filename), but caches results for subsequent calls""" 45 if filename not in _cache: 46 _cache[filename] = Load(filename) 47 # Return a copy of the object so that any changes a caller makes won't affect 48 # the next caller. 49 return copy.deepcopy(_cache[filename]) 50 51