本文整理汇总了Python中simplejson.load方法的典型用法代码示例。如果您正苦于以下问题:Python simplejson.load方法的具体用法?Python simplejson.load怎么用?Python simplejson.load使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类simplejson
的用法示例。
在下文中一共展示了simplejson.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _load_connectors
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def _load_connectors(self, main_config):
self.connectors_configs = {}
if main_config.get("connectors"):
for connector in main_config['connectors']:
try:
connector_class = TBUtility.check_and_import(connector["type"], self._default_connectors.get(connector["type"], connector.get("class")))
self._implemented_connectors[connector["type"]] = connector_class
with open(self._config_dir + connector['configuration'], 'r', encoding="UTF-8") as conf_file:
connector_conf = load(conf_file)
if not self.connectors_configs.get(connector['type']):
self.connectors_configs[connector['type']] = []
connector_conf["name"] = connector["name"]
self.connectors_configs[connector['type']].append({"name": connector["name"], "config": {connector['configuration']: connector_conf}})
except Exception as e:
log.error("Error on loading connector:")
log.exception(e)
else:
log.error("Connectors - not found! Check your configuration!")
main_config["remoteConfiguration"] = True
log.info("Remote configuration is enabled forcibly!")
示例2: __load_iterator_config
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def __load_iterator_config(self):
if not self.__iterator_file_name:
if not self.__resolve_iterator_file():
log.error("[%s] Unable to load iterator configuration from file: file name is not resolved",
self.get_name())
return False
try:
iterator_file_path = Path(self.__config_dir + self.__iterator_file_name)
if not iterator_file_path.exists():
return False
with iterator_file_path.open("r") as iterator_file:
self.__iterator = load(iterator_file)
log.debug("[%s] Loaded iterator configuration from %s", self.get_name(), self.__iterator_file_name)
except Exception as e:
log.error("[%s] Failed to load iterator configuration from %s: %s",
self.get_name(), self.__iterator_file_name, str(e))
return bool(self.__iterator)
示例3: main
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def main():
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = open(sys.argv[1], 'r')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'r')
outfile = open(sys.argv[2], 'w')
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
with infile:
try:
obj = json.load(infile,
object_pairs_hook=json.OrderedDict,
use_decimal=True)
except ValueError:
raise SystemExit(sys.exc_info()[1])
with outfile:
json.dump(obj, outfile, sort_keys=True, indent=' ', use_decimal=True)
outfile.write('\n')
示例4: test_object_pairs_hook
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def test_object_pairs_hook(self):
s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4),
("qrt", 5), ("pad", 6), ("hoy", 7)]
self.assertEqual(json.loads(s), eval(s))
self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p)
self.assertEqual(json.load(StringIO(s),
object_pairs_hook=lambda x: x), p)
od = json.loads(s, object_pairs_hook=OrderedDict)
self.assertEqual(od, OrderedDict(p))
self.assertEqual(type(od), OrderedDict)
# the object_pairs_hook takes priority over the object_hook
self.assertEqual(json.loads(s,
object_pairs_hook=OrderedDict,
object_hook=lambda x: None),
OrderedDict(p))
示例5: __init__
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def __init__(self, http_error):
"""Create a ServerRequestException from a given urllib2.HTTPError.
Args:
http_error: The HTTPError that the ServerRequestException will be
based on.
"""
error_details = None
if http_error.fp:
try:
error_body = json.load(http_error.fp)
error_details = ['%s: %s' % (detail['message'], detail['debug_info'])
for detail in error_body['error']['errors']]
except (ValueError, TypeError, KeyError):
pass
if error_details:
error_message = ('HTTP %s (%s) error when communicating with URL: %s. '
'Details: %s' % (http_error.code, http_error.reason,
http_error.filename, error_details))
else:
error_message = ('HTTP %s (%s) error when communicating with URL: %s.' %
(http_error.code, http_error.reason,
http_error.filename))
super(ServerRequestException, self).__init__(error_message)
示例6: add_async_request
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def add_async_request(self, method, relative_url, headers, body, source_ip,
server_name=None, version=None, instance_id=None):
"""Dispatch an HTTP request asynchronously.
Args:
method: A str containing the HTTP method of the request.
relative_url: A str containing path and query string of the request.
headers: A list of (key, value) tuples where key and value are both str.
body: A str containing the request body.
source_ip: The source ip address for the request.
server_name: An optional str containing the server name to service this
request. If unset, the request will be dispatched to the default
server.
version: An optional str containing the version to service this request.
If unset, the request will be dispatched to the default version.
instance_id: An optional str containing the instance_id of the instance to
service this request. If unset, the request will be dispatched to
according to the load-balancing for the server and version.
"""
fake_socket = FakeRequestSocket(method, relative_url, headers, body)
self._server.AddEvent(0, lambda: (fake_socket, (source_ip, self._port)))
示例7: main
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def main():
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = open(sys.argv[2], 'wb')
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
try:
obj = json.load(infile,
object_pairs_hook=json.OrderedDict,
use_decimal=True)
except ValueError, e:
raise SystemExit(e)
示例8: _try_load_json
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def _try_load_json(self, jsonfile):
logger.debug("Loading json configuration from %s" % jsonfile)
fd = None
try:
fd = open(jsonfile)
except Exception as e:
logger.debug(
"Error reading configuration file %s: %s; "
"ignoring..." % (jsonfile, e)
)
return {}
config = None
try:
config = json.load(fd)
except Exception as e:
logger.error(
"Error parsing configuration file %s: %s" % (jsonfile, e)
)
return {}
logger.trace("contents read from %s: %s" % (jsonfile, config))
return config
示例9: load_config
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def load_config(yaml_file):
logger.debug("Loading configuration from %s" % yaml_file)
fd = None
try:
fd = open(yaml_file)
except Exception as e:
logger.error(
"Error reading configuration file %s, ignoring..." % yaml_file
)
return
try:
return yaml.load(fd, Loader=yaml.FullLoader)
except Exception as e:
logger.error(
"Error parsing configuration file %s: %s" % (yaml_file, e)
)
return
示例10: get_host_info
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def get_host_info(self):
''' Get variables about a specific host '''
if len(self.index) == 0:
# Need to load index from cache
self.load_index_from_cache()
if self.args.host not in self.index:
# try updating the cache
self.do_api_calls_update_cache()
if self.args.host not in self.index:
# host might not exist anymore
return self.json_format_dict({}, True)
(region, instance_id) = self.index[self.args.host]
instance = self.get_instance(region, instance_id)
return self.json_format_dict(self.get_host_info_dict_from_instance(instance), True)
示例11: load
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def load(self):
con = sqlite3.connect(self.tmp_cookie_file)
cur = con.cursor()
cur.execute('select host, path, isSecure, expiry, name, value from moz_cookies '
'where host like "%{}%"'.format(self.domain_name))
cj = http.cookiejar.CookieJar()
for item in cur.fetchall():
c = create_cookie(*item)
cj.set_cookie(c)
con.close()
self.__add_session_cookies(cj)
self.__add_session_cookies_lz4(cj)
return cj
示例12: read_config
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def read_config(config_file):
config_file = os.path.abspath(os.path.expanduser(config_file))
if not os.path.isfile(config_file):
print_err("Config file not found!")
sys.exit(1)
with open(config_file, "r") as f:
config = json.load(f)
if "session" not in config:
config["session"] = "SESSION"
if "fuzzer" not in config:
config["fuzzer"] = "afl-fuzz"
return config
示例13: load
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def load(source_dir: Union[os.PathLike, str]) -> Any:
"""
Load an object from a directory, saved by
``gordo.serializer.pipeline_serializer.dump``
This take a directory, which is either top-level, meaning it contains
a sub directory in the naming scheme: "n_step=<int>-class=<path.to.Class>"
or the aforementioned naming scheme directory directly. Will return that
unsterilized object.
Parameters
----------
source_dir: Union[os.PathLike, str]
Location of the top level dir the pipeline was saved
Returns
-------
Union[GordoBase, Pipeline, BaseEstimator]
"""
# This source dir should have a single pipeline entry directory.
# may have been passed a top level dir, containing such an entry:
with open(os.path.join(source_dir, "model.pkl"), "rb") as f:
return pickle.load(f)
示例14: load
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def load(self):
"""
Extract tabular data as |TableData| instances from a dict object.
|load_source_desc_text|
:rtype: |TableData| iterator
.. seealso::
:py:meth:`.JsonTableFileLoader.load()`
"""
self._validate()
self._logger.logging_load()
formatter = JsonTableFormatter(self.source)
formatter.accept(self)
return formatter.to_table_data()
示例15: main
# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import load [as 别名]
def main():
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = open(sys.argv[2], 'wb')
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
try:
obj = simplejson.load(infile)
except ValueError, e:
raise SystemExit(e)