Python中使用 JSON

Python中使用 JSON

原文:http://www.pythonclub.org/modules/jsonjavascript

JSON是JavaScript Object Notation的縮寫,SJON是一種輕量級的數據交換格式。易於人閱讀和編寫。同時也易於機器解析和生成。html

它基於JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一個子集。java

JSON採用徹底獨立於語言的文本格式,可是也使用了相似於C語言家族的習慣(包括C, C++, C#, Java, JavaScript,Perl, Python等)。python

這些特性使JSON成爲理想的數據交換語言。json

Python在2.6之後的版本中報好了JSON模塊,能夠直接在Python中import json.api

Python 2.7 使用JSON 模塊

Python 2.7中自帶了JSON模塊,直接import json就能夠使用了。ui

#! /tools/cfr/bin/python import json  
 
s = '[{"name":"niaochao","point":{"lat":"39.990","lng":"116.397"},"desc":"aoyunhuizhuchangdi"},{"name":"beidapingpangqiuguan","point":{"lat":"39.988","lng":"116.315"},"desc":"pingpangqiubisaichangdi"},{"name":"beijinggongrentiyuchang","point":{"lat":"39.930","lng":"116.446"},"desc":"zuqiubisaichangdi"}]'  locations = json.loads(s)  print str(len(locations))  for location in locations:  
    print location["name"]  
    print location["point"]["lat"]

結果爲:spa

3
niaochao
39.990
beidapingpangqiuguan
39.988
beijinggongrentiyuchang
39.930

Python 2.5 安裝 JSON模塊

可是對已Python 2.5之前的版本,這須要咱們下載json模塊。code

首先從http://pypi.python.org/pypi/python-json下載python-json, 而後安裝。htm

解壓zip包 而後把json.py minjson.py 拷到 /usr/lib/python2.5/下面就好了。

怎樣使用請看:http://docs.python.org/library/json.html

Python 2.5 JSON應用實例

import json  
 
s = '[{"name":"niaochao","point":{"lat":"39.990","lng":"116.397"},"desc":"aoyunhuizhuchangdi"},{"name":"beidapingpangqiuguan","point":{"lat":"39.988","lng":"116.315"},"desc":"pingpangqiubisaichangdi"},{"name":"beijinggongrentiyuchang","point":{"lat":"39.930","lng":"116.446"},"desc":"zuqiubisaichangdi"}]'  locations = json.read(s)  print str(len(locations))  for location in locations:  
    print location["name"]  
    print location["point"]["lat"]

參考

相關文章
相關標籤/搜索