当前位置: 首页>>代码示例>>Python>>正文


Python json.load方法代码示例

本文整理汇总了Python中json.load方法的典型用法代码示例。如果您正苦于以下问题:Python json.load方法的具体用法?Python json.load怎么用?Python json.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在json的用法示例。


在下文中一共展示了json.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_props_write

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def test_props_write(self):
        announce('test_props_write')
        report = True
        self.env.pwrite(self.env.model_nm + ".props")
        with open(self.env.model_nm + ".props", "r") as f:
            props_written = json.load(f)
        if len(props_written) != len(self.env.props.props):
            report = False
        if report:
            for key in props_written:
                if key not in self.env.props.props:
                    report = False
                    break
                else:
                    if props_written[key]["val"] != self.env.props.props[key].val:
                        report = False
                        break
        f.close()
        os.remove(self.env.model_nm + ".props")
        self.assertEqual(report, True) 
开发者ID:gcallah,项目名称:indras_net,代码行数:22,代码来源:test_basic.py

示例2: get_prev_models

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def get_prev_models(filepath):
    """
        Reads from models.json, which also happens to be our DEST_FOLDER
        If our DEST_FOLDER doesn't exist, it will just create the new file
        Otherwise, it will read in the json,
        so the script knows the model ID for exisiting models
    """
    try:
        with open(filepath, 'r') as input_stream:
            try:
                # Assumes models.json has DB_NAME that matches
                # what the script expects
                return json.load(input_stream)[DB_NAME]
            except ValueError:
                script_output("Invalid JSON in " + filepath)
                exit(1)

    except OSError:
        script_output("Could not open " + filepath)
        exit(1) 
开发者ID:gcallah,项目名称:indras_net,代码行数:22,代码来源:json_combiner.py

示例3: get_models

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def get_models(model_files):
    """
        return all the models from list of model files (.json) for processing
    """
    model = []
    for file in model_files:
        if file.endswith("_model.json"):
            with open(file, 'r') as input_stream:
                try:
                    loadedData = json.load(input_stream)
                    if(len(loadedData) > 0):
                        model.append(loadedData)
                except ValueError:
                    script_output("Invalid JSON in " + file)
                    exit(1)
        else:
            script_output("File does not end with _model.json found")
            script_output(file, False)
            exit(1)

    return model 
开发者ID:gcallah,项目名称:indras_net,代码行数:23,代码来源:json_combiner.py

示例4: main

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def main(args=None):
    welcome = "Welcome to Indra! Please choose a model:"
    stars = "*" * len(welcome)
    model_db = None
    model_list = None
    with open("models.json", 'r') as f:
        model_db = json.load(f)
    model_list = model_db["models_database"]
    while True:
        print("\n",
              stars, "\n",
              welcome, "\n",
              stars)
        for choice, model in enumerate(model_list):
            print(str(choice) + ". ", model["name"])
        choice = int(input())
        if 0 <= choice < len(model_list):
            rdict[model_list[choice]["run"]]()
        else:
            return 0 
开发者ID:gcallah,项目名称:indras_net,代码行数:22,代码来源:__main__.py

示例5: _get_classes_from_json

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def _get_classes_from_json(self):

        for filename in ("labels.txt", "classes.json"):
            path = os.path.join(self.samples_dir, filename)
            if not os.path.exists(path):
                raise VergeMLError("{} is missing".format(filename))

            with open(path) as f:
                if filename == "labels.txt":
                    items = filter(None, map(methodcaller("strip"), f.read().splitlines()))
                    labels = Labels(items)
                else:
                    self.classes = json.load(f)
        files = {}
        # prefix the sample with input_dir
        for k, v in self.classes['files'].items():

            # on windows and linux, separator is /
            path = k.split("/")
            path.insert(0, self.samples_dir)
            fname = os.path.join(*path)
            files[fname] = v

        self.classes['files'] = files
        self.meta['labels'] = labels 
开发者ID:mme,项目名称:vergeml,代码行数:27,代码来源:labeled_image.py

示例6: __init__

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def __init__(self, user_agent, token_url_template, platform):
        self.user_agent = user_agent
        self.token_url_template = token_url_template
        self.platform = platform

        self.session = requests.Session()
        self.session.cookies = http.cookiejar.LWPCookieJar()
        if not os.path.exists(COOKIE_FILE):
            self.session.cookies.save(COOKIE_FILE)
        self.session.cookies.load(COOKIE_FILE, ignore_discard=True)
        self.session.headers = {"User-agent": user_agent}
        if os.path.exists(SESSION_FILE):
            self.load()
        else:
            self._state = {
                'api_key': None,
                'client_api_key': None,
                'token': None,
                'access_token': None,
                'access_token_expiry': None
            }
        self.login() 
开发者ID:kmac,项目名称:mlbv,代码行数:24,代码来源:session.py

示例7: assess

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def assess(self, ctx: Context, challenge_num: int):
        """
        Gets information about a specific CyberStart Assess level and challenge.
        """

        NO_HINTS_MSG = f"**:warning: Remember, other people can't give hints after challenge {HINTS_LIMIT}**"

        # Gather Assess data from JSON file.
        with open("cdbot/data/assess.json") as f:
            assess_docs = load(f)

        if not 0 < challenge_num <= len(assess_docs):
            await ctx.send("Invalid challenge number!")

        else:
            # Select the needed challenge
            challenge_raw = assess_docs[challenge_num - 1]
            challenge_title = challenge_raw["title"]
            challenge_difficulty = challenge_raw["difficulty"]
            challenge_text = challenge_raw["description"]

            if challenge_num > HINTS_LIMIT:
                challenge_text = NO_HINTS_MSG + "\n" + challenge_text

            embed = Embed(
                title=f"CyberStart Assess Challenge {challenge_num} - {challenge_title}",
                description=challenge_text,
                colour=0x4262F4,
                url=f"https://assess.joincyberdiscovery.com/challenge-{challenge_num:02d}",
            )
            embed.set_author(name="Cyber Discovery", icon_url=CYBERDISC_ICON_URL)
            embed.set_footer(text=f"Difficulty: {challenge_difficulty}")

            await ctx.send(embed=embed) 
开发者ID:CyberDiscovery,项目名称:cyberdisc-bot,代码行数:36,代码来源:cyber.py

示例8: read_config

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def read_config(stream, env):
    config = {}
    try:
        config['tags'] = json.load(stream)
    except ValueError:
        LOG.exception('Failed to decode JSON from input stream')
        config['tags'] = {}

    LOG.debug('Configuration after reading stream: %s', config)

    config['context'] = {
        'branch': env.get('BRANCH'),
        'change': env.get('CHANGE'),
        'commit': env.get('COMMIT'),
        'ps': env.get('PATCHSET'),
    }

    LOG.info('Final configuration: %s', config)

    return config 
开发者ID:airshipit,项目名称:drydock,代码行数:22,代码来源:image_tags.py

示例9: register

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def register(self, name, serializer):
        """Register ``serializer`` object under ``name``.

        Raises :class:`AttributeError` if ``serializer`` in invalid.

        .. note::

            ``name`` will be used as the file extension of the saved files.

        :param name: Name to register ``serializer`` under
        :type name: ``unicode`` or ``str``
        :param serializer: object with ``load()`` and ``dump()``
            methods

        """
        # Basic validation
        getattr(serializer, 'load')
        getattr(serializer, 'dump')

        self._serializers[name] = serializer 
开发者ID:TKkk-iOSer,项目名称:wechat-alfred-workflow,代码行数:22,代码来源:workflow.py

示例10: filename_to_url

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def filename_to_url(filename: str, cache_dir: Union[str, Path] = None) -> Tuple[str, str]:
    """
    Return the url and etag (which may be ``None``) stored for `filename`.
    Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
    """
    if cache_dir is None:
        cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
    if isinstance(cache_dir, Path):
        cache_dir = str(cache_dir)

    cache_path = os.path.join(cache_dir, filename)
    if not os.path.exists(cache_path):
        raise FileNotFoundError("file {} not found".format(cache_path))

    meta_path = cache_path + '.json'
    if not os.path.exists(meta_path):
        raise FileNotFoundError("file {} not found".format(meta_path))

    with open(meta_path) as meta_file:
        metadata = json.load(meta_file)
    url = metadata['url']
    etag = metadata['etag']

    return url, etag 
开发者ID:ymcui,项目名称:cmrc2019,代码行数:26,代码来源:file_utils.py

示例11: build_from_pb

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def build_from_pb(self):
		with tf.gfile.FastGFile(self.FLAGS.pbLoad, "rb") as f:
			graph_def = tf.GraphDef()
			graph_def.ParseFromString(f.read())
		
		tf.import_graph_def(
			graph_def,
			name=""
		)
		with open(self.FLAGS.metaLoad, 'r') as fp:
			self.meta = json.load(fp)
		self.framework = create_framework(self.meta, self.FLAGS)

		# Placeholders
		self.inp = tf.get_default_graph().get_tensor_by_name('input:0')
		self.feed = dict() # other placeholders
		self.out = tf.get_default_graph().get_tensor_by_name('output:0')
		
		self.setup_meta_ops() 
开发者ID:AmeyaWagh,项目名称:Traffic_sign_detection_YOLO,代码行数:21,代码来源:build.py

示例12: savepb

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def savepb(self):
		"""
		Create a standalone const graph def that 
		C++	can load and run.
		"""
		darknet_pb = self.to_darknet()
		flags_pb = self.FLAGS
		flags_pb.verbalise = False
		
		flags_pb.train = False
		# rebuild another tfnet. all const.
		tfnet_pb = TFNet(flags_pb, darknet_pb)		
		tfnet_pb.sess = tf.Session(graph = tfnet_pb.graph)
		# tfnet_pb.predict() # uncomment for unit testing
		name = 'built_graph/{}.pb'.format(self.meta['name'])
		os.makedirs(os.path.dirname(name), exist_ok=True)
		#Save dump of everything in meta
		with open('built_graph/{}.meta'.format(self.meta['name']), 'w') as fp:
			json.dump(self.meta, fp)
		self.say('Saving const graph def to {}'.format(name))
		graph_def = tfnet_pb.sess.graph_def
		tf.train.write_graph(graph_def,'./', name, False) 
开发者ID:AmeyaWagh,项目名称:Traffic_sign_detection_YOLO,代码行数:24,代码来源:build.py

示例13: test_CLI_JSON_YOLOv1

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def test_CLI_JSON_YOLOv1():
    #Test predictions outputted to a JSON file using the YOLOv1 model through CLI
    #NOTE: This test verifies that the code executes properly, the JSON file is created properly and the predictions generated are within a certain
    #      margin of error when compared to the expected predictions.

    testString = "flow --imgdir {0} --model {1} --load {2} --config {3} --threshold 0.4 --json".format(os.path.dirname(testImg["path"]), yolo_small_CfgPath, yolo_small_WeightPath, generalConfigPath)
    executeCLI(testString)

    outputJSONPath = os.path.join(os.path.dirname(testImg["path"]), "out", os.path.splitext(os.path.basename(testImg["path"]))[0] + ".json")
    assert os.path.exists(outputJSONPath), "Expected output JSON file: {0} was not found.".format(outputJSONPath)

    with open(outputJSONPath) as json_file:
        loadedPredictions = json.load(json_file)

    assert compareObjectData(testImg["expected-objects"]["yolo-small"], loadedPredictions, testImg["width"], testImg["height"], threshCompareThreshold, posCompareThreshold), "Generated object predictions from JSON were not within margin of error compared to expected values."
    os.remove(outputJSONPath) #Remove the JSON file so that it does not affect subsequent tests 
开发者ID:AmeyaWagh,项目名称:Traffic_sign_detection_YOLO,代码行数:18,代码来源:test_darkflow.py

示例14: test_vectors

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def test_vectors():
    with open("vectors.json", "r") as f:
        vectors = json.load(f)
    for description, mnemonics, secret in vectors:
        if secret:
            assert bytes.fromhex(secret) == shamir.combine_mnemonics(
                mnemonics, b"TREZOR"
            ), 'Incorrect secret for test vector "{}".'.format(description)
        else:
            with pytest.raises(MnemonicError):
                shamir.combine_mnemonics(mnemonics)
                pytest.fail(
                    'Failed to raise exception for test vector "{}".'.format(
                        description
                    )
                ) 
开发者ID:trezor,项目名称:python-shamir-mnemonic,代码行数:18,代码来源:test_shamir.py

示例15: __init__

# 需要导入模块: import json [as 别名]
# 或者: from json import load [as 别名]
def __init__(self, config_file):
        self.mode = None

        self.vmac_mode = None
        self.vmac_options = None

        self.vnhs = None

        self.refmon = None

        self.flanc_auth = None

        self.route_server = None

        self.arp_proxy = None

        self.peers = {}

        # loading config file
        config = json.load(open(config_file, 'r'))

        # parse config
        self.parse_config(config) 
开发者ID:sdn-ixp,项目名称:iSDX,代码行数:25,代码来源:lib.py


注:本文中的json.load方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。