Python2.x自学笔记(一)——Json格式与请求
生活随笔
收集整理的這篇文章主要介紹了
Python2.x自学笔记(一)——Json格式与请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
?
簡單請求
# 簡單的請求響應 import urllib2response = urllib2.urlopen('http://www.baidu.com/') html = response.read() print html或
import urllib2request = urllib2.Request('http://www.baidu.com/') response = urllib2.urlopen(request) html = response.read() print html?
JSON操作
JSON對象直接使用
其實就是dict
import jsonbody_value = {"name":"張三","data":{"cmdtype":"test","currpage":"0","pagesize":"10"}} print json.dumps(body_value, ensure_ascii=False)JSON未轉義字符串在loads后使用
import jsonbody_value = '{"name":"張三","data":{"cmdtype":"test","currpage":"0","pagesize":"10"}}' decoded = json.loads(body_value) print 'name:',decoded['name'] print 'data.cmdtype:',decoded['data']['cmdtype'] print json.dumps(decoded, ensure_ascii=False)結果為:
name: 張三 data.cmdtype: test {"data": {"currpage": "0", "pagesize": "10", "cmdtype": "test"}, "name": "張三"}ensure_ascii=False不加的話,中文不會被顯示正確
在dumps()中添加indent=4后,可格式化json:
print json.dumps(decoded, ensure_ascii=False, indent=4) {"data": {"currpage": "0", "pagesize": "10", "cmdtype": "test"}, "name": "張三" }在dumps()中添加sort_keys=True后,可將JSON屬性排序:
print json.dumps(decoded, indent=4, sort_keys=True, ensure_ascii=False) {"data": {"cmdtype": "test", "currpage": "0", "pagesize": "10"}, "name": "張三" }JSON有轉義字符的字符串在loads后使用
import jsonbody_value = '''{"name":"張三","data":{\"cmdtype\":\"test\",\"currpage\":0,\"pagesize\":10}} ''' decoded = json.loads(body_value) print decoded.keys() print json.dumps(decoded, sort_keys=True, ensure_ascii=False, indent=4)結果:
[u'data', u'name'] {"data": {"cmdtype": "test", "currpage": 0, "pagesize": 10}, "name": "張三" }json.loads與eval的區別
import jsonbody_value = "{\"name\":\"張三\",\"data\":{\"cmdtype\":\"test\",\"currpage\":0,\"pagesize\":10}}"decoded = eval(body_value) print decoded.keys() print json.dumps(decoded, sort_keys=True, ensure_ascii=False, indent=4) decoded = json.loads(body_value) print decoded.keys() print json.dumps(decoded, sort_keys=True, ensure_ascii=False, indent=4)結果:
['data', 'name'] {"data": {"cmdtype": "test", "currpage": 0, "pagesize": 10}, "name": "張三" } [u'data', u'name'] {"data": {"cmdtype": "test", "currpage": 0, "pagesize": 10}, "name": "張三" }?
發送JSON格式請求
import httplib import jsondef http_post():requrl = 'http://localhost:8999/query/normal'headerdata = {"Content-type": "application/json"}body_value = {"name":"張三","data":{"cmdtype":"test","currpage":"0","pagesize":"10"}}conn = httplib.HTTPConnection("localhost", 8999)conn.request('POST', requrl, json.dumps(body_value), headerdata)response = conn.getresponse()return response.read()data = http_post() print data?
轉載于:https://my.oschina.net/woooooody/blog/1154056
總結
以上是生活随笔為你收集整理的Python2.x自学笔记(一)——Json格式与请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hyper-V 2016:支持guest
- 下一篇: ST:看物联网老兵的平台化战略雄心