【Python進階】03、json

來源:互聯網
上載者:User

標籤:【python進階】03、json

     本節學習如何使用 Python 語言來編碼和解碼 JSON 對象。

這裡的編碼不是指字元編碼,而是指把python對象轉化為能在網路上或其它介質上傳輸的文本資訊。

一、json簡介

JSON: JavaScript Object Notation(JavaScript 物件標記法)

JSON 是儲存和交換文本資訊的文法。類似 XML。

JSON 比 XML 更小、更快,更易解析。

       JSON 使用 Javascript文法來描述資料對象,但是 JSON 仍然獨立於語言和平台。JSON 解析器和 JSON 庫支援許多不同的程式設計語言。 目前非常多的動態(PHP,JSP,.NET)程式設計語言都支援JSON。


JSON 執行個體
{"sites": [{ "name":"菜鳥教程" , "url":"www.runoob.com" }, { "name":"google" , "url":"www.google.com" }, { "name":"微博" , "url":"www.weibo.com" }]}

這個 sites 對象是包含 3 個網站記錄(對象)的數組。

類似Python的dict


json文法規則:

  • 資料在成對的名稱和數值中

  • 資料由逗號分隔

  • 花括弧儲存對象

  • 方括弧儲存數組


二、json模組

In [4]: import jsonIn [5]: json.json.JSONDecoder  json.dump         json.load         json.JSONEncoder  json.dumps        json.loads        json.decoder      json.encoder      json.scanner

encode 將 Python 對象編碼成 JSON 字串
decode

將已編碼的 JSON 字串解碼為 Python 對象

python與json支援以下幾種結構轉化:

|  Supports the following objects and types by default:     |       |  +-------------------+---------------+     |  | Python            | JSON          |     |  +===================+===============+     |  | dict              | object        |     |  +-------------------+---------------+     |  | list, tuple       | array         |     |  +-------------------+---------------+     |  | str, unicode      | string        |     |  +-------------------+---------------+     |  | int, long, float  | number        |     |  +-------------------+---------------+     |  | True              | true          |     |  +-------------------+---------------+     |  | False             | false         |     |  +-------------------+---------------+     |  | None              | null          |     |  +-------------------+---------------+

案例:有一個儲存使用者資訊的json檔案,需要解析json為User類。

User = nametuple(‘User‘, [‘name‘, ‘age‘, ‘gender‘, ‘phone‘, ‘mail‘])

[[email protected] src]# cat text.json{"users": [    {        "name": "xj",        "age": 25,        "gender": "man",        "phone": "15711112222",        "mail": "[email protected]"    }]}

解決方案:

      解析json為字典,再處理字典

      使用object_hook

In [3]: ret = json.load(open("/tmp/src/text.json"))In [4]: retOut[4]: {u‘users‘: [{u‘age‘: 25,   u‘gender‘: u‘man‘,   u‘mail‘: u‘[email protected]‘,   u‘name‘: u‘xj‘,   u‘phone‘: u‘15711112222‘}]}In [5]: type(ret)Out[5]: dictIn [6]: ret.ret.clear       ret.items       ret.pop         ret.viewitemsret.copy        ret.iteritems   ret.popitem     ret.viewkeysret.fromkeys    ret.iterkeys    ret.setdefault  ret.viewvaluesret.get         ret.itervalues  ret.update      ret.has_key     ret.keys        ret.values    In [7]: ret[‘users‘]Out[7]: [{u‘age‘: 25,  u‘gender‘: u‘man‘,  u‘mail‘: u‘[email protected]‘,  u‘name‘: u‘xj‘,  u‘phone‘: u‘15711112222‘}]    In [16]: type(ret[‘users‘])Out[16]: listIn [17]: ret[‘users‘][0]Out[17]: {u‘age‘: 25, u‘gender‘: u‘man‘, u‘mail‘: u‘[email protected]‘, u‘name‘: u‘xj‘, u‘phone‘: u‘15711112222‘} In [19]: ret[‘users‘][0]["age"]Out[19]: 25


【Python進階】03、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.