gpt4 book ai didi

Python - 格式化 JSON 输出到文件

转载 作者:行者123 更新时间:2023-11-28 20:43:40 30 4
gpt4 key购买 nike

我有一个 Python 对象方法,它使用 json 模块将有序字典对象的集合作为 JSON 字符串写入具有 UTF-8 编码的文件。这是代码:

 def write_small_groups_JSON_file( self, file_dir, file_name ):

with io.open( file_dir + file_name, 'w', encoding='utf-8' ) as file:
JSON_obj = ''
i = 0
for ID in self.small_groups.keys():
JSON_obj = json.dumps( self.small_groups[ID]._asdict(), ensure_ascii=False )
file.write( unicode( JSON_obj ) )
i += 1

print str( i ) + ' small group JSON objects successfully written to the file ' + \
file.name + '.'

这里 small_groups 是名为 SmallGroup 的命名元组对象的有序字典,其键 ID 形式的元组(N,M) 其中 N,M 是正整数,如果 ID in small_groups.keys() 那么 small_groups[ID]._asdict () 是有序字典。以下是 ID=(36,1) 的示例:

OrderedDict([('desc', ''), ('order', 36), ('GAP_ID', (36, 1)),
('GAP_desc', ''), ('GAP_pickled_ID', ''), ('is_abelian', None),
('is_cyclic', None), ('is_simple', None), ('is_nilpotent', None),
('nilpotency_class', None), ('is_solvable', None), ('derived_length',
None), ('is_pgroup', None), ('generators', None), ('char_degrees',
'[[1,4],[2,8]]'), ('D3', 68), ('MBS_STPP_param_type', (36, 1, 1)),
('Beta0', 36)])

文件中的 JSON 输出看起来是压扁的,对象之间没有逗号,也没有左右大括号。看起来像这样

{ object1 }{ object 2 }.....
...........{ object n }.....

这是有效的 JSON 格式,还是我必须使用逗号分隔对象?

此外,如果我在某个地方有一个模式,是否有一种方法可以根据它验证输出?

最佳答案

不,您不再拥有有效的 JSON;您将单独的 JSON 对象(每个对象都有效)写入一个没有任何分隔符的文件。

您必须编写自己的分隔符,先生成一个长列表,然后再将其写出。

创建列表非常简单:

objects = []
for small_group in self.small_groups.values():
objects.append(small_group._asdict()))
with io.open( file_dir + file_name, 'w', encoding='utf-8' ) as file:
json_object = json.dumps(objects, ensure_ascii=False)
file.write(unicode(json_object))

print '{} small group JSON objects successfully written to the file {}.'.format(
len(objects), file.name)

这会写出 JSON 一次,生成包含多个对象的 JSON 列表。

如果您要自己注入(inject)分隔符,则必须从编写 [ 开始,然后在您生成的每个 JSON 对象后写一个逗号除了最后一个 ,您将在其中编写 ] :

with io.open( file_dir + file_name, 'w', encoding='utf-8' ) as file:
file.write(u'[')
for count, small_group in enumerate(self.small_groups.values()):
if count: # not the first
file.write(u',')
json_object = json.dumps(small_group, ensure_ascii=False)
file.write(unicode(json_object))
file.write(u']')

print '{} small group JSON objects successfully written to the file {}.'.format(
len(self.small_groups), file.name)

一旦您拥有有效的 JSON,您就可以使用 JSON 架构验证器对其进行验证。 Python 的明显选择是 Python jsonschema library .

关于Python - 格式化 JSON 输出到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28501135/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com