Python simplejson.dump方法代码示例

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

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

示例1: main

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [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


示例2: test_namedtuple_dump

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def test_namedtuple_dump(self):
        for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:
            d = v._asdict()
            sio = StringIO()
            json.dump(v, sio)
            self.assertEqual(d, json.loads(sio.getvalue()))
            sio = StringIO()
            json.dump(v, sio, namedtuple_as_object=True)
            self.assertEqual(
                d,
                json.loads(sio.getvalue()))
            sio = StringIO()
            json.dump(v, sio, tuple_as_array=False)
            self.assertEqual(d, json.loads(sio.getvalue()))
            sio = StringIO()
            json.dump(v, sio, namedtuple_as_object=True,
                      tuple_as_array=False)
            self.assertEqual(
                d,
                json.loads(sio.getvalue())) 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:22,代码来源:test_namedtuple.py


示例3: test_tuple_array_dump

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def test_tuple_array_dump(self):
        t = (1, 2, 3)
        expect = json.dumps(list(t))
        # Default is True
        sio = StringIO()
        json.dump(t, sio)
        self.assertEqual(expect, sio.getvalue())
        sio = StringIO()
        json.dump(t, sio, tuple_as_array=True)
        self.assertEqual(expect, sio.getvalue())
        self.assertRaises(TypeError, json.dump, t, StringIO(),
                          tuple_as_array=False)
        # Ensure that the "default" does not get called
        sio = StringIO()
        json.dump(t, sio, default=repr)
        self.assertEqual(expect, sio.getvalue())
        sio = StringIO()
        json.dump(t, sio, tuple_as_array=True, default=repr)
        self.assertEqual(expect, sio.getvalue())
        # Ensure that the "default" gets called
        sio = StringIO()
        json.dump(t, sio, tuple_as_array=False, default=repr)
        self.assertEqual(
            json.dumps(repr(t)),
            sio.getvalue()) 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:27,代码来源:test_tuple.py


示例4: load

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [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


示例5: _write

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def _write(f,stylized_network,config,G):
    """Internal function to write the everything to a json-file."""
    if G is not None:
        js_G = nx.node_link_data(G)
    else:
        js_G = None
    json.dump({
                'stylized_network' : stylized_network,
                'config' : config,
                'Graph' : js_G
              },
              f,
              separators=(',', ':'),
              ) 
开发者ID:benmaier,项目名称:netwulf,代码行数:18,代码来源:io.py


示例6: save

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def save(self, path):
        """
        Save stance into JSON file.
        Parameters
        ----------
        path : string
            Path to JSON file.
        """
        d = {}
        if self.com is not None:
            d['com'] = {"pos": list(self.com.p)}
        if self.left_foot is not None:
            d['left_foot'] = self.left_foot.dict_repr
        if self.right_foot is not None:
            d['right_foot'] = self.right_foot.dict_repr
        if self.left_hand is not None:
            d['left_hand'] = self.left_hand.dict_repr
        if self.right_hand is not None:
            d['right_hand'] = self.right_hand.dict_repr
        with open(path, 'w') as fp:
            simplejson.dump(d, fp, indent=4, sort_keys=True) 
开发者ID:stephane-caron,项目名称:pymanoid,代码行数:24,代码来源:stance.py


示例7: serialize_report

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def serialize_report(self, output_file, report_data):
        """
        Serialize the data given as a Python dictionary into the format
        supported by this plugin.
        :param output_file: Output file for this report plugin.
        :type output_file: str
        :param report_data: Report data returned by :ref:`get_report_data`().
        :type report_data: dict(str -> *)
        """
        beautify = Config.audit_config.boolean(
            Config.plugin_args.get("beautify", "no"))
        with open(output_file, "wb") as fp:
            if beautify:
                dump(report_data, fp, sort_keys=True, indent=4)
            else:
                dump(report_data, fp)
    #-------------------------------------------------------------------------- 
开发者ID:blackye,项目名称:luscan-devel,代码行数:23,代码来源:json.py


示例8: writeOutCategories

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def writeOutCategories(self, dirName, comparisons=None, labelRefs=None):
    """
    For models which define categories with bitmaps, log the categories (and
    their relative distances) to a JSON specified by the dirName. The JSON will
    contain the dict of category bitmaps, and if specified, dicts of label
    references and category bitmap comparisons.
    """
    if not hasattr(self, "categoryBitmaps"):
      raise TypeError("This model does not have category encodings compatible "
                      "for logging.")
    if not os.path.isdir(dirName):
      raise ValueError("Invalid path to write file.")
    with open(os.path.join(dirName, "category_distances.json"), "w") as f:
      catDict = {"categoryBitmaps":self.categoryBitmaps,
                 "labelRefs":dict(enumerate(labelRefs)) if labelRefs else None,
                 "comparisons":comparisons if comparisons else None}
      json.dump(catDict,
                f,
                sort_keys=True,
                indent=2,
                separators=(",", ": ")) 
开发者ID:numenta,项目名称:nupic.fluent,代码行数:25,代码来源:classification_model.py


示例9: setUp

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def setUp(self):
        self.json_file = tempfile() + ".json"
        fo = open(self.json_file, "w")
        for record in looney_records():
            json.dump(record, fo)
            fo.write("\n")
        fo.close()
        self.csv_file = tempfile() + ".csv"
        fo = open(self.csv_file, "w")
        write = csv.writer(fo).writerow
        get = itemgetter("first", "last", "type")
        for record in looney_records():
            write(get(record))
        fo.close()
        self.schema_file = tempfile()
        fo = open(self.schema_file, "w")
        fo.write(SCHEMA)
        fo.close() 
开发者ID:pluralsight,项目名称:spavro,代码行数:22,代码来源:test_script.py


示例10: completed

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def completed(self, input_data, input_directory, output_directory):
        # The output directory structure should match input directory structure.
        relpath_of_input_file = os.path.relpath(input_data['file'], input_directory)
        relparent_of_input_file = os.path.dirname(relpath_of_input_file)
        inp_filename,inp_extension = os.path.splitext(os.path.basename(relpath_of_input_file))
        output_filedir = os.path.join(output_directory, relparent_of_input_file)
        if not os.path.exists(output_filedir):
            os.makedirs(output_filedir)
        output_filepath =  os.path.join(output_filedir, inp_filename + '.json')
        print(output_filepath)
        with open(output_filepath, 'w') as f:
            json.dump(self.full_report, f, indent=4, separators=(',', ': '))
        return {'file':output_filepath} 
开发者ID:pathbreak,项目名称:deepvisualminer,代码行数:23,代码来源:jsonreportwriter.py


示例11: write_json

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def write_json(file_path, data, do_clear=False):
    """Write `data` to the JSON file specified by `file_path`, optionally clearing the file before
    adding `data`
    Parameters
    ----------
    file_path: String
        The target .json file path to which `data` will be written
    data: Object
        The content to save at the .json file given by `file_path`
    do_clear: Boolean, default=False
        If True, the contents of the file at `file_path` will be cleared before saving `data`"""
    if do_clear is True:
        clear_file(file_path)
    with open(file_path, "w") as f:
        json.dump(data, f, default=default_json_write, tuple_as_array=False) 
开发者ID:HunterMcGushion,项目名称:hyperparameter_hunter,代码行数:19,代码来源:file_utils.py


示例12: main

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def main():
    json_data = dict()
    with open('data/token_migration.csv') as f:
        data = csv.reader(f, delimiter=',')
        shor_per_quanta = int(config.dev.shor_per_quanta)
        count = 0
        for row in data:
            count += 1
            json_data[row[0]] = int(Decimal(row[1]) * shor_per_quanta)
        if count != len(json_data.keys()):
            raise Exception('There must be duplicate address in csv file.')
    with open('data/token_migration.json', 'w') as f:
        json.dump(json_data, f) 
开发者ID:theQRL,项目名称:QRL,代码行数:19,代码来源:token_migration_json_converter.py


示例13: test_cload_other_options

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def test_cload_other_options():
    runner = CliRunner()
    with runner.isolated_filesystem():
        meta = {"foo": "bar", "number": 42}
        with open("meta.json", "w") as f:
            json.dump(meta, f)
        extra_args = [
            "--metadata",
            "meta.json",
            "--zero-based",
            "--storage-options",
            "shuffle=True,fletcher32=True,compression=lzf",
        ]
        result = _run_cload_pairs(runner, 2, extra_args)
        assert result.exit_code == 0
        c = cooler.Cooler("toy.2.cool")
        assert c.info["metadata"] == meta
        with c.open("r") as h5:
            dset = h5["bins/start"]
            assert dset.shuffle
            assert dset.fletcher32
            assert dset.compression == "lzf" 
开发者ID:mirnylab,项目名称:cooler,代码行数:24,代码来源:test_cli_ingest.py


示例14: convert_sql_to_avsc

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def convert_sql_to_avsc(self, avsc_file_path, sql_file_path):
        with open(sql_file_path) as sql_file:
            sql_content = sql_file.read()
        converter = RedshiftSQLToAVSCConverter(
            sql_content=sql_content,
            base_namespace=self.options.base_namespace,
            default_schema=self.options.default_schema
        )
        avro = converter.avro_record
        with open(avsc_file_path, 'w') as avsc_file:
            self.log.info('Writing "{0}"'.format(avsc_file_path))
            json.dump(
                obj=avro,
                fp=avsc_file,
                indent='    ',
                sort_keys=True
            ) 
开发者ID:Yelp,项目名称:data_pipeline,代码行数:19,代码来源:redshift_sql_to_avsc.py


示例15: main

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def main():
    # handle inputs
    args = handleArgs()
    # check for sudo/root privileges
    if not checkSudo():
        exit('You need to be root/sudo ... exiting')
    try:
        am = ActiveMapper(range(1, int(args['range'])))
        hosts = am.scan(args['interface'])
        pp.pprint(hosts)
        # save file
        if args['save']:
            with open(args['save'], 'w') as fp:
                json.dump(hosts, fp)
        return hosts
    except KeyboardInterrupt:
        exit('You hit ^C, exiting PassiveMapper ... bye')
    except:
        print "Unexpected error:", sys.exc_info()
        exit('bye ... ') 
开发者ID:AllGloryToTheHypnotoad,项目名称:netscan2,代码行数:26,代码来源:ascan.py


示例16: main

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [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:
        try:
            obj = json.load(infile,
                            object_pairs_hook=json.OrderedDict,
                            use_decimal=True)
        except ValueError, e:
            raise SystemExit(e)
        json.dump(obj, outfile, sort_keys=True, indent='    ', use_decimal=True)
        outfile.write('\n') 
开发者ID:uwdata,项目名称:termite-visualizations,代码行数:23,代码来源:tool.py


示例17: create_json_output

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def create_json_output(options, sample_file_path, decoded_strings, stack_strings, static_strings):
    """
    Create a report of the analysis performed by FLOSS
    :param options: parsed options
    :param sample_file_path: path of the sample analyzed
    :param decoded_strings: list of decoded strings ([DecodedString])
    :param stack_strings: list of stack strings ([StackString])
    :param static_strings: iterable of static strings ([String])
    """
    strings = {'stack_strings': sanitize_strings_iterator(stack_strings),
               'decoded_strings': sanitize_strings_iterator(decoded_strings),
               'static_strings': sanitize_strings_iterator(static_strings)}
    metadata = {'file_path': sample_file_path,
                'date': datetime.datetime.now().isoformat(),
                'stack_strings': not options.no_stack_strings,
                'decoded_strings': not options.no_decoded_strings,
                'static_strings': not options.no_static_strings}
    report = {'metadata': metadata, 'strings': strings}
    try:
        with open(options.json_output_file, 'w') as f:
            json.dump(report, f, iterable_as_array=True)
    except Exception:
        raise 
开发者ID:fireeye,项目名称:flare-floss,代码行数:25,代码来源:main.py


示例18: Save

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def Save(self, save_as = None):
        if save_as is not None:
            self.path = save_as + POD_FILE_SUFFIX
            self.path_db = save_as + POD_DB_SUFFIX
        if self.path is None:
            self.path = POD_FILE + POD_FILE_SUFFIX
            self.path_db = POD_FILE + POD_DB_SUFFIX
        try:
            self.last_command_db_id = self.log()
        except:
            pass
        try:
            with open(self.path, "w") as stream:
                json.dump(self.__dict__, stream, indent=4, sort_keys=True)
        except:
            pass 
开发者ID:winemug,项目名称:omnipy,代码行数:21,代码来源:pod.py


示例19: test_indent0

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def test_indent0(self):
        h = {3: 1}
        def check(indent, expected):
            d1 = json.dumps(h, indent=indent)
            self.assertEqual(d1, expected)
            sio = StringIO()
            json.dump(h, sio, indent=indent)
            self.assertEqual(sio.getvalue(), expected)
        # indent=0 should emit newlines
        check(0, '{\n"3": 1\n}')
        # indent=None is more compact
        check(None, '{"3": 1}') 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:16,代码来源:test_indent.py


示例20: test_namedtuple_dump_false

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def test_namedtuple_dump_false(self):
        for v in [Value(1), Point(1, 2)]:
            l = list(v)
            sio = StringIO()
            json.dump(v, sio, namedtuple_as_object=False)
            self.assertEqual(
                l,
                json.loads(sio.getvalue()))
            self.assertRaises(TypeError, json.dump, v, StringIO(),
                tuple_as_array=False, namedtuple_as_object=False) 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:12,代码来源:test_namedtuple.py


示例21: test_asdict_not_callable_dump

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def test_asdict_not_callable_dump(self):
        for f in CONSTRUCTORS:
            self.assertRaises(TypeError,
                json.dump, f(DeadDuck()), StringIO(), namedtuple_as_object=True)
            sio = StringIO()
            json.dump(f(DeadDict()), sio, namedtuple_as_object=True)
            self.assertEqual(
                json.dumps(f({})),
                sio.getvalue()) 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:11,代码来源:test_namedtuple.py


示例22: dumps

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def dumps(self, obj, **kw):
        sio = StringIO()
        json.dump(obj, sio, **kw)
        res = json.dumps(obj, **kw)
        self.assertEqual(res, sio.getvalue())
        return res 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:8,代码来源:test_decimal.py


示例23: test_decimal_defaults

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def test_decimal_defaults(self):
        d = Decimal('1.1')
        # use_decimal=True is the default
        self.assertRaises(TypeError, json.dumps, d, use_decimal=False)
        self.assertEqual('1.1', json.dumps(d))
        self.assertEqual('1.1', json.dumps(d, use_decimal=True))
        self.assertRaises(TypeError, json.dump, d, StringIO(),
                          use_decimal=False)
        sio = StringIO()
        json.dump(d, sio)
        self.assertEqual('1.1', sio.getvalue())
        sio = StringIO()
        json.dump(d, sio, use_decimal=True)
        self.assertEqual('1.1', sio.getvalue()) 
开发者ID:gkudos,项目名称:qgis-cartodb,代码行数:16,代码来源:test_decimal.py


示例24: test_dump

# 需要导入模块: import simplejson [as 别名]
# 或者: from simplejson import dump [as 别名]
def test_dump(self):
        sio = StringIO()
        json.dump({}, sio)
        self.assertEquals(sio.getvalue(), '{}') 
开发者ID:linuxscout,项目名称:mishkal,代码行数:6,代码来源:test_dump.py



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