from _ctypes import PyObj_FromPtr
import json
import re
classNoIndent(object):""" Value wrapper. """def__init__(self, value):
self.value = value
classMyEncoder(json.JSONEncoder):
FORMAT_SPEC ='@@{}@@'
regex = re.compile(FORMAT_SPEC.format(r'(\d+)'))def__init__(self,**kwargs):# Save copy of any keyword argument values needed for use here.
self.__sort_keys = kwargs.get('sort_keys',None)super(MyEncoder, self).__init__(**kwargs)defdefault(self, obj):return(self.FORMAT_SPEC.format(id(obj))ifisinstance(obj, NoIndent)elsesuper(MyEncoder, self).default(obj))defencode(self, obj):
format_spec = self.FORMAT_SPEC # Local var to expedite access.
json_repr =super(MyEncoder, self).encode(obj)# Default JSON.# Replace any marked-up object ids in the JSON repr with the# value returned from the json.dumps() of the corresponding# wrapped Python object.for match in self.regex.finditer(json_repr):# see https://stackoverflow.com/a/15012814/355230id=int(match.group(1))
no_indent = PyObj_FromPtr(id)
json_obj_repr = json.dumps(no_indent.value, sort_keys=self.__sort_keys)# Replace the matched id string with json formatted representation# of the corresponding Python object.
json_repr = json_repr.replace('"{}"'.format(format_spec.format(id)), json_obj_repr)return json_repr
#input json file
json_data ={}
grid_list =[["j2690","j2701"],["j2690","j2701"]]
time_list =[123456789,987654321]for did in["7286","5131"]:
path_list =[]for i inrange(len(grid_list)):
path_list.append({"path_t":time_list[i],"path_p":NoIndent(grid_list[i])})print(path_list)
json_data[did]= path_list
withopen('path.json','w')as fw:# 整理格式,list部分不换行
json_data = json.dumps(json_data, cls=MyEncoder, ensure_ascii=False, sort_keys=True, indent=2)
fw.write(json_data)
fw.write('\n')