Python文件之----JSON

时间:2015-06-02 08:04:45   收藏:0   阅读:208
#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文件截图:

技术分享

原文:http://www.cnblogs.com/moye13/p/4545403.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!