用户工具

站点工具


modules:json

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

modules:json [2014/05/14 13:22] (当前版本)
行 1: 行 1:
 +====== Python中使用 JSON  ======
  
 +JSON是JavaScript Object Notation的缩写,SJON是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。
 +
 +它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 ​
 +
 +JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C,​ C++, C#, Java, JavaScript, Perl, Python等)。
 +
 +这些特性使JSON成为理想的数据交换语言。
 +
 +Python在2.6以后的版本中报好了JSON模块,可以直接在Python中import json.
 +
 +===== Python 2.7 使用JSON 模块 =====
 +
 +Python 2.7中自带了JSON模块,直接import json就可以使用了。
 +
 +<code python>
 +#! /​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"​]
 +</​code>​
 +
 +结果为:
 +<​code>​
 +3
 +niaochao
 +39.990
 +beidapingpangqiuguan
 +39.988
 +beijinggongrentiyuchang
 +39.930
 +</​code>​
 +
 +===== Python 2.5 安装 JSON模块 =====
 +但是对已Python 2.5以前的版本,这需要我们下载json模块。
 +
 +首先从http://​pypi.python.org/​pypi/​python-json下载python-json,​ 然后安装。
 +
 +解压zip包 然后把json.py minjson.py 拷到 /​usr/​lib/​python2.5/​下面就行了。
 +
 +怎样使用请看:http://​docs.python.org/​library/​json.html
 +
 +==== Python 2.5 JSON应用实例 ====
 +
 +
 +<code 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.read(s)  ​
 +print str(len(locations))  ​
 +for location in locations:  ​
 +    print location["​name"​]  ​
 +    print location["​point"​]["​lat"​]  ​
 +</​code>​
 +
 +
 +===== 参考 =====
 +  * http://​docs.python.org/​library/​json.html
 +  * http://​pypi.python.org/​pypi/​python-json
modules/json.txt · 最后更改: 2014/05/14 13:22 (外部编辑)