本文整理汇总了Python中simplejson.dump方法的典型用法代码示例。如果您正苦于以下问题:Python simplejson.dump方法的具体用法?Python simplejson.dump怎么用?Python simplejson.dump使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类simplejson
的用法示例。
在下文中一共展示了simplejson.dump方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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')
示例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()))
示例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())
示例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)
示例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=(',', ':'),
)
示例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)
示例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)
#--------------------------------------------------------------------------
示例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=(",", ": "))
示例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()
示例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}
示例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)
示例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)
示例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"
示例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
)
示例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 ... ')