當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。