Python的字典和JSON在表現形式上非常相似
#這是Python中的一個字典 dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' } //這是javascript中的一個JSON對象 json_obj = { 'str': 'this is a string', 'arr': [1, 2, 'a', 'b'], 'sub_obj': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }
實際上JSON就是Python字典的字符串表示,但是字典作為一個復雜對象是無法直接轉換成定義它的代碼的字符串(不能傳遞所以需要將其轉換成字符串先),Python有一個叫simplejson的庫可以方便的完成JSON的生成和解析,這個包已經包含在Python2.6中,就叫json 主要包含四個方法: dump和dumps(從Python生成JSON),load和loads(解析JSON成Python的數據類型)dump和dumps的唯一區別是dump會生成一個類文件對象,dumps會生成字符串,同理load和loads分別解析類文件對象和字符串格式的JSON
import json dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' } json.dumps(dic) #output: #'{"sub_dic": {"sub_str": "this is sub str", "sub_list": [1, 2, 3]}, "end": "end", "list": [1, 2, "a", "b"], "str": "this is a string"}'
1
#
coding=utf-8
2
3
import
httplib
4
import
json
5
conn
=
httplib.HTTPConnection(
"
m.weather.com.cn
"
)
6
conn.request(
"
GET
"
,
"
/data/101110101.html
"
)
7
weather
=
conn.getresponse()
8
info
=
weather.read()
9
weatherinfo
=
json.loads(info)
10
print
weatherinfo[
'
weatherinfo
'
][
'
city
'
],
11
conn.close()
1
>>>
================================
RESTART
================================
2
>>>
3
西安
4
>>>
