/tools/grit/grit/gather/json_loader.py

https://github.com/lianliuwei/chromium_base
Python | 53 lines | 20 code | 9 blank | 24 comment | 1 complexity | 09b0d0709ee499537444828bbee307c0 MD5 | raw file
  1. # Copyright (c) 2010 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. import types
  5. from grit.gather import interface
  6. from grit import util
  7. class JsonLoader(interface.GathererBase):
  8. '''A simple gatherer that loads and parses a JSON file.'''
  9. def __init__(self, json_text):
  10. '''Initializes a gatherer object with JSON input.
  11. Args:
  12. json_text: A string containing a JSON expression.
  13. '''
  14. super(type(self), self).__init__()
  15. self._json_text = json_text
  16. self._data = None
  17. def Parse(self):
  18. '''Parses the text of self._json_text into the data structure in
  19. self._data.
  20. '''
  21. globs = {}
  22. exec('data = ' + self._json_text, globs)
  23. self._data = globs['data']
  24. def GetData(self):
  25. '''Returns the parsed JSON data.'''
  26. return self._data
  27. def FromFile(filename_or_stream, extkey, encoding):
  28. '''Creates a JSONLoader instance from a file or stream.
  29. Args:
  30. filename_or_stream: The source of JSON data.
  31. extkey: Unused, see interface.py.
  32. encoding: The encoding used in the JSON file. (Note that it should
  33. not contain localized strings.)
  34. Returns:
  35. The JSONLoader instance holding the JSON data unparsed.
  36. '''
  37. if isinstance(filename_or_stream, types.StringTypes):
  38. filename_or_stream = \
  39. util.WrapInputStream(file(filename_or_stream, 'rU'), encoding)
  40. return JsonLoader(filename_or_stream.read())
  41. FromFile = staticmethod(FromFile)