目录

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就可以使用了。

#! /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"]

结果为:

3
niaochao
39.990
beidapingpangqiuguan
39.988
beijinggongrentiyuchang
39.930

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应用实例

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"]  

参考