如果有一个json文件它可能这样存储json信息:
{"000001":{"09:25:00.000":["149000","163900","134100","149000","149000","true"],"09:26:00.000":["149000","163900","134100","149000","149000","true"]}."000002":{"09:25:00.000":["149000","163900","134100","149000","149000","true"],"09:26:00.000":["149000","163900","134100","149000","149000","149000","149000","0","0","0","true"]}}
然而我们希望的是这样的:
{ "000001": { "09:25:00.000": [ "149000", "163900", "134100", "149000", "149000", "true" ], "09:26:00.000":[ "149000", "163900", "134100", "149000", "149000", "true" ] }, "000002": { "09:25:00.000": [ "149000", "163900", "134100", "149000", "149000", "true" ], "09:26:00.000":[ "149000", "163900", "134100", "149000", "149000", "true" ] } }
所以就需要使用工具进行格式化,那么,python就可以派上用场了。
如果需要格式化的文件很小,只需要在命令行输出格式化后的字符串了,那么linux中有一条指令:
python -m json.tool filename如果文件很大,那么就需要将格式化的信息输入到一个新的文件中,就需要使用python:
写一个python文件,命名为:JFormat.py
#coding:utf-8 import json import codecs from collections import OrderedDict import sys if(len(sys.argv)!=3): print('the number of argv is not 3, but ', len(sys.argv)) with codecs.open(sys.argv[1], 'r', 'utf-8') as f: jtext = f.read() jdict = json.loads(jtext, object_pairs_hook=OrderedDict) with codecs.open(sys.argv[2], 'w', 'utf-8') as f2: json.dump(jdict, f2, indent=2)运行时:
python JFormat.py filename1 filename2