python介面自動化5-Json資料處理

來源:互聯網
上載者:User

標籤:欄位   ===   url   返回   content   value   res   odi   類型   

前言

有些post的請求參數是json格式的,這個前面第二篇post請求裡面提到過,需要匯入json模組處理。

一般常見的介面返回資料也是json格式的,我們在做判斷時候,往往只需要提取其中幾個關鍵的參數就行,這時候就需要json來解析返回的資料了。

一、json模組簡介

1.Json簡介:Json,全名 JavaScript Object Notation,是一種輕量級的資料交換格式,常用於http請求中

2.可以用help(json),查看對應的源碼注釋內容

Encoding basic Python object hierarchies::              >>> import json         >>> json.dumps([‘foo‘, {‘bar‘: (‘baz‘, None, 1.0, 2)}])         ‘["foo", {"bar": ["baz", null, 1.0, 2]}]‘         >>> print json.dumps("\"foo\bar")         "\"foo\bar"         >>> print json.dumps(u‘\u1234‘)         "\u1234"         >>> print json.dumps(‘\\‘)         "\\"         >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)         {"a": 0, "b": 0, "c": 0}         >>> from StringIO import StringIO         >>> io = StringIO()         >>> json.dump([‘streaming API‘], io)         >>> io.getvalue()         ‘["streaming API"]‘

 

 

二、Encode(python->json)

1.首先說下為什麼要encode,python裡面bool值是True和False,json裡面bool值是true和false,並且區分大小寫,這就尷尬了,明明都是bool值。

在python裡面寫的代碼,傳到json裡,肯定識別不了,所以需要把python的代碼經過encode後成為json可識別的資料類型。

2.舉個簡單例子,中dict類型經過json.dumps()後變成str,True變成了true,False變成了fasle

3.以下對應關係表是從json模組的源碼裡面爬出來的.python的資料類,經過encode成json的資料類型,對應的表如下      |  | Python              | JSON          |      |  +===================+===============+      |  | dict                  | object        |      |  +-------------- -----+---------------+      |  | list, tuple          | array         |      |  +-------------------+---------------+      |  | str, unicode      | string        |      |  +-------------------+---------------+      |  | int, long, float  | number        |      |  +-------------------+---------------+      |  | True                | true          |      |  +-------------------+---------------+      |  | False             | false         |      |  +-------------------+---------------+      |  | None              | null          |      |  +-------------------+---------------+

 

三、decode(json->python)

1.以第三篇的登入成功結果:{"success":true}為例,我們其實最想知道的是success這個欄位返回的是True還是False

2.如果以content位元組輸出,返回的是一個字串:{"success":true},這樣擷取後面那個結果就不方便了

3.如果經過json解碼後,返回的就是一個字典:{u‘success‘: True},這樣擷取後面那個結果,就用字典的方式去取值:result2["success"]

4.同樣json資料轉化成python可識別的資料,對應的表關係如下

|  +---------------+-------------------+      |  | JSON               | Python            |      |  +===============+===================+      |  | object             | dict              |      |  +---------------+-------------------+      |  | array               | list              |      |  +---------------+-------------------+      |  | string              | unicode           |      |  +---------------+-------------------+      |  | number (int)    | int, long         |      |  +---------------+-------------------+      |  | number (real)   | float             |      |  +---------------+-------------------+      |  | true                | True              |      |  +---------------+-------------------+      |  | false               | False             |      |  +---------------+-------------------+      |  | null                 | None              |      |  +---------------+-------------------+

 

四、案例分析

1.比如開啟快遞網:http://www.kuaidi.com/,搜尋某個單號,判斷它的狀態是不是已簽收

2. 實現代碼如下

 

五、參考代碼:

# coding:utf-8 import requests
url = "http://www.kuaidi.com/index-ajaxselectcourierinfo-1202247993797-yunda.html" headers = {             "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0"            }  # get方法其它加個ser-Agent就可以了
s = requests.session() r = s.get(url, headers=headers,verify=False) result = r.json() data = result["data"]   # 擷取data裡面內容 print data print data[0]         # 擷取data裡最上面有個 get_result = data[0][‘context‘]  # 擷取已簽收狀態 print get_result
if u"已簽收" in get_result:     print "快遞單已簽收成功" else:     print "未簽收"

python介面自動化5-Json資料處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.