【python教程】Python JSON

來源:互聯網
上載者:User

Python JSON

本章節我們將為大家介紹如何使用 Python 語言來編碼和解碼 JSON 對象。

環境配置

在使用 Python 編碼或解碼 JSON 資料前,我們需要先安裝 JSON 模組。本教程我們會下載 Demjson 並安裝:

$tar xvfz demjson-1.6.tar.gz$cd demjson-1.6$python setup.py install

JSON 函數


函數

描述


encode 將 Python 對象編碼成 JSON 字串

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

encode

Python encode() 函數用於將 Python 對象編碼成 JSON 字串。

文法

demjson.encode(self, obj, nest_level=0)

執行個體

以下執行個體將數組編碼為 JSON 格式資料:

#!/usr/bin/pythonimport demjsondata = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]json = demjson.encode(data)print json

以上代碼執行結果為:

[{"a":1,"b":2,"c":3,"d":4,"e":5}]

decode

Python 可以使用 demjson.decode() 函數解碼 JSON 資料。該函數返回 Python 欄位的資料類型。

文法

demjson.decode(self, txt)

執行個體

以下執行個體展示了Python 如何解碼 JSON 對象:

#!/usr/bin/pythonimport demjsonjson = '{"a":1,"b":2,"c":3,"d":4,"e":5}';text = demjson.decode(json)print  text

以上代碼執行結果為:

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}

以上就是【python教程】Python JSON的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!


  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.