標籤:
#coding=utf-8import jsondef 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檔案:
Python檔案之----JSON