當前位置: 首頁>>代碼示例>>Python>>正文


Python simplejson.load方法代碼示例

本文整理匯總了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!") 
開發者ID:thingsboard,項目名稱:thingsboard-gateway,代碼行數:22,代碼來源:tb_gateway_service.py

示例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) 
開發者ID:thingsboard,項目名稱:thingsboard-gateway,代碼行數:22,代碼來源:odbc_connector.py

示例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') 
開發者ID:gkudos,項目名稱:qgis-cartodb,代碼行數:24,代碼來源:tool.py

示例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)) 
開發者ID:gkudos,項目名稱:qgis-cartodb,代碼行數:18,代碼來源:test_decode.py

示例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) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:26,代碼來源:endpointscfg.py

示例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))) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:23,代碼來源:dev_appserver.py

示例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) 
開發者ID:linuxscout,項目名稱:mishkal,代碼行數:20,代碼來源:tool.py

示例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 
開發者ID:mendix,項目名稱:cf-mendix-buildpack,代碼行數:25,代碼來源:config.py

示例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 
開發者ID:mendix,項目名稱:cf-mendix-buildpack,代碼行數:20,代碼來源:config.py

示例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) 
開發者ID:haproxytech,項目名稱:cloud-blueprints,代碼行數:20,代碼來源:ec2.py

示例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 
開發者ID:borisbabic,項目名稱:browser_cookie3,代碼行數:18,代碼來源:__init__.py

示例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 
開發者ID:rc0r,項目名稱:afl-utils,代碼行數:19,代碼來源:afl_multicore.py

示例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) 
開發者ID:equinor,項目名稱:gordo,代碼行數:26,代碼來源:serializer.py

示例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() 
開發者ID:thombashi,項目名稱:pytablereader,代碼行數:21,代碼來源:core.py

示例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) 
開發者ID:tvalacarta,項目名稱:tvalacarta,代碼行數:18,代碼來源:tool.py


注:本文中的simplejson.load方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。