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


Python json5.dumps方法代碼示例

本文整理匯總了Python中json5.dumps方法的典型用法代碼示例。如果您正苦於以下問題:Python json5.dumps方法的具體用法?Python json5.dumps怎麽用?Python json5.dumps使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在json5的用法示例。


在下文中一共展示了json5.dumps方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def main():
    argv = sys.argv
    if len(argv) == 2:
        arg_groups = params.parse(sys.argv[1])
        for args, config in arg_groups:
            trainer = Trainer(args)
            states = trainer.train()
            with open('models/log.jsonl', 'a') as f:
                f.write(json5.dumps({
                    'data': os.path.basename(args.data_dir),
                    'params': config,
                    'state': states,
                }))
                f.write('\n')
    elif len(argv) == 3 and '--dry' in argv:
        argv.remove('--dry')
        arg_groups = params.parse(sys.argv[1])
        pprint([args.__dict__ for args, _ in arg_groups])
    else:
        print('Usage: "python train.py configs/xxx.json5"') 
開發者ID:alibaba-edu,項目名稱:simple-effective-text-matching-pytorch,代碼行數:22,代碼來源:train.py

示例2: test_skip_keys

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_skip_keys(self):
        od = OrderedDict()
        od[(1, 2)] = 2
        self.assertRaises(TypeError, json5.dumps, od)
        self.assertEqual(json5.dumps(od, skipkeys=True), '{}')

        od['foo'] = 1
        self.assertEqual(json5.dumps(od, skipkeys=True), '{foo: 1}')

        # Also test that having an invalid key as the last element
        # doesn't incorrectly add a trailing comma (see
        # https://github.com/dpranke/pyjson5/issues/33).
        od = OrderedDict()
        od['foo'] = 1
        od[(1, 2)] = 2
        self.assertEqual(json5.dumps(od, skipkeys=True), '{foo: 1}') 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:18,代碼來源:lib_test.py

示例3: _render

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def _render(self):
        """ Writes the current config to file. """
        new_config = json5.dumps(self.config)
        with open(self.path, 'w') as f:
            log.info('rewriting ContainerPilot config: %s', new_config)
            f.write(new_config) 
開發者ID:autopilotpattern,項目名稱:mysql,代碼行數:8,代碼來源:config.py

示例4: check

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def check(self, obj, s):
        self.assertEqual(json5.dumps(obj), s) 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:4,代碼來源:lib_test.py

示例5: test_allow_duplicate_keys

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_allow_duplicate_keys(self):
        self.assertIn(json5.dumps({1: "foo", "1": "bar"}),
                      {'{"1": "foo", "1": "bar"}',
                       '{"1": "bar", "1": "foo"}'})

        self.assertRaises(ValueError, json5.dumps,
                          {1: "foo", "1": "bar"},
                           allow_duplicate_keys=False) 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:10,代碼來源:lib_test.py

示例6: test_check_circular

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_check_circular(self):
        # This tests a trivial cycle.
        l = [1, 2, 3]
        l[2] = l
        self.assertRaises(ValueError, json5.dumps, l)

        # This checks that json5 doesn't raise an error. However,
        # the underlying Python implementation likely will.
        try:
            json5.dumps(l, check_circular=False)
            self.fail()  # pragma: no cover
        except Exception as e:
            self.assertNotIn(str(e), 'Circular reference detected')

        # This checks that repeated but non-circular references
        # are okay.
        x = [1, 2]
        y = {"foo": x, "bar": x}
        self.check(y,
                   '{foo: [1, 2], bar: [1, 2]}')

        # This tests a more complicated cycle.
        x = {}
        y = {}
        z = {}
        z['x'] = x
        z['y'] = y
        z['x']['y'] = y
        z['y']['x'] = x
        self.assertRaises(ValueError, json5.dumps, z) 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:32,代碼來源:lib_test.py

示例7: test_default

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_default(self):

        def _custom_serializer(obj):
            del obj
            return 'something'

        self.assertRaises(TypeError, json5.dumps, set())
        self.assertEqual(json5.dumps(set(), default=_custom_serializer),
                         'something') 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:11,代碼來源:lib_test.py

示例8: test_ensure_ascii

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_ensure_ascii(self):
        self.check(u'\u00fc', '"\\u00fc"')
        self.assertEqual(json5.dumps(u'\u00fc', ensure_ascii=False),
                         u'"\u00fc"') 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:6,代碼來源:lib_test.py

示例9: test_numbers

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_numbers(self):
        self.check(15, '15')
        self.check(1.0, '1.0')
        self.check(float('inf'), 'Infinity')
        self.check(float('-inf'), '-Infinity')
        self.check(float('nan'), 'NaN')

        self.assertRaises(ValueError, json5.dumps,
                          float('inf'), allow_nan=False) 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:11,代碼來源:lib_test.py

示例10: test_non_string_keys

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_non_string_keys(self):
        self.assertEqual(json5.dumps({False: 'a', 1: 'b', 2.0: 'c', None: 'd'}),
                         '{"false": "a", "1": "b", "2.0": "c", "null": "d"}') 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:5,代碼來源:lib_test.py

示例11: test_quote_keys

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_quote_keys(self):
        self.assertEqual(json5.dumps({"foo": 1}, quote_keys=True),
                         '{"foo": 1}') 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:5,代碼來源:lib_test.py

示例12: test_sort_keys

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_sort_keys(self):
        od = OrderedDict()
        od['foo'] = 1
        od['bar'] = 2
        self.assertEqual(json5.dumps(od, sort_keys=True),
                         '{bar: 2, foo: 1}') 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:8,代碼來源:lib_test.py

示例13: test_empty_key

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_empty_key(self):
        self.assertEqual(json5.dumps({'': 'value'}), '{"": "value"}') 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:4,代碼來源:lib_test.py

示例14: test_object_roundtrip

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def test_object_roundtrip(self, input_object):
        dumped_string_json = json.dumps(input_object)
        dumped_string_json5 = json5.dumps(input_object)

        parsed_object_json = json5.loads(dumped_string_json)
        parsed_object_json5 = json5.loads(dumped_string_json5)

        assert parsed_object_json == input_object
        assert parsed_object_json5 == input_object 
開發者ID:dpranke,項目名稱:pyjson5,代碼行數:11,代碼來源:lib_test.py

示例15: __init__

# 需要導入模塊: import json5 [as 別名]
# 或者: from json5 import dumps [as 別名]
def __init__(self, config, resume, model, optimizer, loss_function):
        self.n_gpu = torch.cuda.device_count()
        self.device = self._prepare_device(self.n_gpu, cudnn_deterministic=config["cudnn_deterministic"])

        self.model = model.to(self.device)

        if self.n_gpu > 1:
            self.model = torch.nn.DataParallel(self.model, device_ids=list(range(self.n_gpu)))

        self.optimizer = optimizer

        self.loss_function = loss_function

        # Trainer
        self.epochs = config["trainer"]["epochs"]
        self.save_checkpoint_interval = config["trainer"]["save_checkpoint_interval"]
        self.validation_config = config["trainer"]["validation"]
        self.validation_interval = self.validation_config["interval"]
        self.find_max = self.validation_config["find_max"]
        self.validation_custom_config = self.validation_config["custom"]

        self.start_epoch = 1
        self.best_score = -np.inf if self.find_max else np.inf
        self.root_dir = Path(config["root_dir"]) / config["experiment_name"]
        self.checkpoints_dir = self.root_dir / "checkpoints"
        self.logs_dir = self.root_dir / "logs"
        prepare_empty_dir([self.checkpoints_dir, self.logs_dir], resume=resume)

        self.writer = visualization.writer(self.logs_dir.as_posix())
        self.writer.add_text(
            tag="Configuration",
            text_string=f"<pre>  \n{json5.dumps(config, indent=4, sort_keys=False)}  \n</pre>",
            global_step=1
        )

        if resume: self._resume_checkpoint()

        print("Configurations are as follows: ")
        print(json5.dumps(config, indent=2, sort_keys=False))

        with open((self.root_dir / f"{time.strftime('%Y-%m-%d-%H-%M-%S')}.json").as_posix(), "w") as handle:
            json5.dump(config, handle, indent=2, sort_keys=False)

        self._print_networks([self.model]) 
開發者ID:haoxiangsnr,項目名稱:IRM-based-Speech-Enhancement-using-LSTM,代碼行數:46,代碼來源:base_trainer.py


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