Python文件之----JSON
#coding=utf-8import json def writeJSON(filaName="test.json"): f=open(filaName, "wb") testDic={"key":"value"} json.dump(testDic,f) f.close() def readJSON(fileName="test.json"): f=file(fileName,"r") s=json.load(f) f.close() print s.keys() print s["key"] def main(): writeJSON() readJSON() if __name__=="__main__": main() ''' 输出: [u'key'] value [Finished in 0.1s] '''
此外对于复杂的json文件,可结合普通文本的写操作,例如写D3用的GeoJson文件:
def writeJSON(filaName="Japan.json"): f=open(filaName, "w") f.write("{\n") f.write(" \"type\": \"FeatureCollection\",\n") f.write(" \"features\": [\n") for i in range(0,len(numOne)): dicProperties={} listcoodinates=[] dicfeature={} dicfeature['type']="Feature" dicgeometry={"type": "Polygon"} temp=[] temp.append(numOne[i]) dicgeometry['coordinates']=temp dicfeature['geometry']=dicgeometry f.write(" ") json.dump(dicfeature, f) if (i== len(numOne)-1): f.write("\n") else: f.write(",\n") f.write(" ]\n") f.write("}") f.close()
Japan.json文件截图: