Python-将JSON输出格式化为文件
我有一个Python对象方法,它使用Python-将JSON输出格式化为文件,python,json,Python,Json,我有一个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
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 + '.'
这里的smallgroups
是一个命名元组对象的有序字典,名为smallgroups
,带有一个键ID
,它是一个形式为(N,M)
的元组,其中N,M
是正整数,如果ID在smallgroups.keys()
中,则smallgroups[ID]。\u asdict()
是一个有序字典。下面是ID=(36,1)
的一个示例:
文件中的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列表
如果您要自己插入分隔符,则必须先编写[
,然后在生成的每个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的明显选择是无效JSON的。。您不应该将单个子元素转换为JSON,然后将它们连接起来:您应该构建一个Python结构,然后在最后转储整个部分
data = []
for key, value in self.small_groups.items():
data.append(value._asdict())
with io.open( file_dir + file_name, 'w', encoding='utf-8' ) as f:
f.write(json.dumps(data))
谢谢,我想您还需要
unicode
符号。我认为JSON数据文件是用大括号括起来的,而不是方括号。@ramius:使用u'['
unicode文本。JSON对象由{..}
括起来,包含键值对(键值总是字符串)。[…]
是一个JSON列表,是其他JSON对象的有序集合。还有一个问题:JSON输出不会保留对象内键的顺序。小组的键顺序。\u asdict()
对象是['desc','order','GAP_ID','GAP_desc','GAP_pickled_ID','is_abelian','is_cyclic','is_simple','is_幂零','lipotency_class','is_solvable','derived_length','is_pgroup','generators','char degrees','D3','MBS_STPP_param_type','Beta0']
,但是JSON对象输出扰乱了这一点。如何保持顺序?这就是为什么我首先使用有序字典的原因!!@ramius:与Python字典一样,JSON对象是无序的。您必须编写一个[键,值]序列
如果顺序很重要,则改为列出。@ramius:如果您传入orderedict
对象本身,而不是使用。\u asdict()
,json.dumps()
应该按照orderedict
对象中列出的相同顺序写出json键值(请参阅),但任何读取JSON的代码仍然可以自由忽略该顺序。
data = []
for key, value in self.small_groups.items():
data.append(value._asdict())
with io.open( file_dir + file_name, 'w', encoding='utf-8' ) as f:
f.write(json.dumps(data))