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